java

public class T {
    
    private static int a =1;//1代表线程1 2线程2
    
    public static void main(String[] args) {
        
        final T t = new T();
        
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                synchronized (t) {
                    for(int i=1;i<=10;i++){
                        if(i==6){
                                try {
                                    a=2;//切换线程2
                                    t.wait();//线程1等待,并释放了对象的锁
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        System.out.println(Thread.currentThread().getName()+":"+i);
                    }                                            
                }
            }
        }).start();;
        
        new Thread(new Runnable(){

            @Override
            public void run() {
                synchronized (t) {
                    if(a!=2){//没有轮到,进入等待
                        try {
                            t.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("hello");
                    t.notifyAll();
    
                }
                
            }
            
        }).start();

    }        
}

 结果如下:

Thread-0:1
Thread-0:2
Thread-0:3
Thread-0:4
Thread-0:5
Thread-1:hello
Thread-0:6
Thread-0:7
Thread-0:8
Thread-0:9
Thread-0:10

原文地址:https://www.cnblogs.com/GotoJava/p/6743043.html