synchronize的wait和notify方法使用
1.锁对象.wait()
线程开始等待进入阻塞队列,并释放已获取的锁
2.锁对象.notify()
通知其他某个等待线程进入就绪态,但不释放锁。
public class ThreadTest {
public static final Integer lock = 1;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(()->{
synchronized (lock){
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
if(i==50){
try {
System.out.println(Thread.currentThread().getName()+"开始等待");
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
});
Thread t2 = new Thread(()->{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (lock){
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
if(i==50){
lock.notify();
System.out.println(Thread.currentThread().getName()+"发出通知");
}
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("主程序程序执行完毕");
}
}