在多线程中通信我们可以使用wait/notify/notifyAll
这里顺带提一下sleep和wait的区别
sleep:线程阻塞不释放锁
wait:线程阻塞释放锁
wait和notify和notifyAll是属于Object的方法所以所有类都可以调用到
notify唤醒阻塞中的线程,但是并不释放锁,需要等待线程执行完毕且释放锁才能由其他线程争夺锁
notifyAll和notify的区别在于notify唤醒是只有随机一个线程执行完其他的任然保持阻塞状态,而notifyAll能保障所有线程都会唤醒执行完
notify效果
public class NotifyTest {
private Integer flag = new Integer(1);
class NotifyThread extends Thread{
public NotifyThread(String name) {
super(name);
}
public void run() {
synchronized (flag) {
try {
sleep(3000);//推迟3秒钟通知
} catch (InterruptedException e) {
e.printStackTrace();
}
flag.notify();
}
}
};
class WaitThread extends Thread {
public WaitThread(String name) {
super(name);
}
public void run() {
synchronized (flag) {
long waitTime = System.currentTimeMillis();
try {
flag.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("wait time :"+waitTime);
}
}
}
public static void main(String[] args) throws InterruptedException {
System.out.println("Main Thread Run!");
NotifyTest test = new NotifyTest();
NotifyThread notifyThread =test.new NotifyThread("notify01");
WaitThread waitThread01 = test.new WaitThread("waiter01");
WaitThread waitThread02 = test.new WaitThread("waiter02");
WaitThread waitThread03 = test.new WaitThread("waiter03");
waitThread01.start();
waitThread02.start();
waitThread03.start();
notifyThread.start();
}
}
notifyAll效果
public class NotifyTest {
private Integer flag = new Integer(1);
class NotifyThread extends Thread{
public NotifyThread(String name) {
super(name);
}
public void run() {
synchronized (flag) {
try {
sleep(3000);//推迟3秒钟通知
} catch (InterruptedException e) {
e.printStackTrace();
}
flag.notifyAll();
}
}
};
class WaitThread extends Thread {
public WaitThread(String name) {
super(name);
}
public void run() {
synchronized (flag) {
long waitTime = System.currentTimeMillis();
try {
flag.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("wait time :"+waitTime);
}
}
}
public static void main(String[] args) throws InterruptedException {
System.out.println("Main Thread Run!");
NotifyTest test = new NotifyTest();
NotifyThread notifyThread =test.new NotifyThread("notify01");
WaitThread waitThread01 = test.new WaitThread("waiter01");
WaitThread waitThread02 = test.new WaitThread("waiter02");
WaitThread waitThread03 = test.new WaitThread("waiter03");
waitThread01.start();
waitThread02.start();
waitThread03.start();
notifyThread.start();
}
}