首页 > 代码库 > 多线程同步 wait notify

多线程同步 wait notify

package test;

public class Test implements Runnable{

    public static int j =0;
    @Override
    public void run() {
            synchronized (this) {
                while (j<30) {
                    System.out.println(Thread.currentThread().getName() + ": " + ++j);  
                    if (j % 3 == 0 && 0 != j) {
                        try {
                            this.notify(); // 唤醒另外一个线程  
                            this.wait(); // 暂时释放资源  
                        } catch (InterruptedException e) {
                            e.printStackTrace();  
                        } 
                    }
                }
            }
    }
    public static void main(String[] args) {
        Runnable run = new Test();
        Thread thread1 = new Thread(run);
        Thread thread2 = new Thread(run);
        
        thread1.start();
        thread2.start();
    }
}
Thread-1: 1
Thread-1: 2
Thread-1: 3
Thread-0: 4
Thread-0: 5
Thread-0: 6
Thread-1: 7
Thread-1: 8
Thread-1: 9
Thread-0: 10
Thread-0: 11
Thread-0: 12
Thread-1: 13
Thread-1: 14
Thread-1: 15
Thread-0: 16
Thread-0: 17
Thread-0: 18
Thread-1: 19
Thread-1: 20
Thread-1: 21
Thread-0: 22
Thread-0: 23
Thread-0: 24
Thread-1: 25
Thread-1: 26
Thread-1: 27
Thread-0: 28
Thread-0: 29
Thread-0: 30

简单的多线程同步的例子,理解:

Thread0先获得对象锁this,THread1在等待,当Thread0进入this.notify(); // 唤醒另外一个线程  此行时,唤醒Thread1,但由于Thread0仍然占据着this对象锁,Thread1还不会进入同步代码块,直到Thread0运行到this.wait(),此时Thread0释放this对象锁,堵塞,Thread1获得对象锁,进入同步代码块,循环...