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:2Thread-0:3Thread-0:4Thread-0:5Thread-1:helloThread-0:6Thread-0:7Thread-0:8Thread-0:9Thread-0:10