Fourth, the communication between the base of java multithreading thread

First, what is the communication between multiple threads

1. Concept: communications between multiple threads, multiple threads in fact, operating the same resources, but different movement operations.

Second, multi-threaded communications simulation emerging issues

1. Demand: a first thread write (input) the user, another thread take read (out) the user to achieve a read, a write operation.

2. Code

// 共享对象
class Res {
    // 姓名
    public String name;
    // 性别
    public String sex;
}
// 生产这线程
class IntThread extends Thread {
    public Res res;
    public IntThread(Res res) {
        this.res = res;
    }
    @Override
    public void run() {
        int count = 0; // 1
        while (true) {
            if (count == 0) {
                res.name = "小红";
                res.sex = "女";
            } else {
                res.name = "小明";
                res.sex = "男";
            }
            count = (count + 1) % 2;// 0 1 0 1 0 1
        }
    }
}
// 读取线程
class OutThread extends Thread {
    public Res res;
    public OutThread(Res res) {
        this.res = res;
    }
    @Override
    public void run() {
        while (true) {
            System.out.println(res.name + "," + res.sex);
        }
    }
}
public class Test0001 {
    public static void main(String[] args) throws InterruptedException {
        Res res = new Res();
        IntThread intThread = new IntThread(res);
        OutThread outThread = new OutThread(res);
        intThread.start();
        outThread.start();
    }
}

3. Results

Note: Data are not confused, causing thread-safety issues

Third, multi-threaded communications simulation to solve the problem

1. Code

// 共享对象
class Res {
    // 姓名
    public String name;
    // 性别
    public String sex;
    // 为true情况下 允许读,不能写
    // 为false情况下 允许写,不能读。
    public boolean flag = false;
}
// 生产这线程
class IntThread extends Thread {
    public Res res;

    public IntThread(Res res) {
        this.res = res;
    }
    @Override
    public void run() {
        int count = 0; // 1
        while (true) {
            synchronized (res) {
                if (res.flag) {
                    try {
                        res.wait();// 釋放当前锁对象
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
                if (count == 0) {
                    res.name = "小红";
                    res.sex = "女";
                } else {
                    res.name = "小明";
                    res.sex = "男";
                }
                count = (count + 1) % 2;// 0 1 0 1 0 1
                res.flag = true;// 标记当前线程为等待
                res.notify();// 唤醒被等待的线程
            }
        }
    }
}
// 读取线程
class OutThread extends Thread {
    public Res res;

    public OutThread(Res res) {
        this.res = res;
    }
    @Override
    public void run() {
        while (true) {
            synchronized (res) {
                try {
                    if (!res.flag) {
                        res.wait();
                    }
                    Thread.sleep(1000);
                } catch (Exception e) {
                    // TODO: handle exception
                }
                System.out.println(res.name + "," + res.sex);
                res.flag = false;
                res.notify();
            }
        }
    }
}
public class Test0001 {
    public synchronized static void main(String[] args) throws InterruptedException {
        Res res = new Res();
        IntThread intThread = new IntThread(res);
        OutThread outThread = new OutThread(res);
        intThread.start();
        outThread.start();
    }
}

2. Results

3. Analyze

3.1. Because it involves the object lock, they must be placed in the synchronized use. Wait, Notify sure to use synchronized inside.

3.2.Wait must tentative thread is currently executing, and release the resource lock, so that other threads can have a chance to run.

Note: Be sure to use thread synchronization, and is the same lock resource

Fourth, small welfare

And sleep the difference 1.wait

For the sleep () method, we first need to know which belongs Thread class. And wait () method, Object belongs to the class.

sleep () method results in a program to suspend the specified time, so that the cpu of the other threads, but his remains were monitoring state, when the specified time is up will automatically resume operation.

During the call to sleep () method, the thread will not release the object lock.

And when the call wait () method, the thread will give up the object lock, into the waiting for this object to wait for the lock pool, only after calling notify for this object () method of the thread before moving object lock pool ready to acquire the object lock into operation .

Fifth, the end of the

Always keep the faith!!!

Published 122 original articles · won praise 64 · views 50000 +

Guess you like

Origin blog.csdn.net/chenmingxu438521/article/details/103777197