wait():令当前线程挂起并放弃CPU、同步资源,使得逼得线程可访问并修改共享资源,而当前线程排队等候在此对资源的访问
notiy():唤醒正在排队等待同步资源的线程中优先级最高者结束等待
notifyAll():唤醒正在排队等待资源的所有线程结束等待。
实现二者交替打印实现线程的通信
/*
- 线程通信
- wait():一旦一个线程执行到wait() 就释放当前的锁。
- notify() :唤醒一个线程
- notifyAll() :唤醒所有线程
- 使用两个线程打印1-100,两个线程交替打印
*/
notify()和wait() 要在锁内
具体模块如下:
synchronized(Object obj){
notify();//这里是唤醒另外被锁的线程 如果没有也没事
....
wait();//这里是锁住当前线程
}
public class TestCommunication {
public static void main(String[] args) {
PrintNum p = new PrintNum();
Thread t1 = new Thread(p);
Thread t2 = new Thread(p);
t1.setName("甲");
t2.setName("乙");
t1.start();
t2.start();
}
}
class PrintNum implements Runnable{
private int num;
public void run() {
while(true) {
synchronized (this) {
if (num <= 100) {
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + num);
num++;
} else {
break;
}
notify();
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}