线程间通讯:
其实就是多个线程在操作同一个资源,但是操作的动作不同。
wait(),notify(),notifyAll(),用来操作线程为什么定义在了Object类中?
1. wait(),notify(),notifyAll()方法都使用在同步中,因为这些方法要对持有监视器(锁)的线程操作(而只有同步才具有锁)
2. 使用这些方法时必须要标识所属的同步的锁。(因为这些方法在操作同步中线程时,都必须要标识它们所操作线程共有的锁,只有同一个锁上的被等待线程,可以被同一个锁上notify唤醒。不可以对不同锁中的线程进行唤醒。也就是说,等待和唤醒必须是同一个锁。)
3. 锁可以是任意对象,所以任意对象调用的方法一定定义Object类中。
wait(),sleep()的区别:
wait():释放cpu执行权,释放锁。
sleep():释放cpu执行权,不释放锁。
public class Res {
private String name;
private String sex;
private boolean flag = false;
public synchronized void set(String name, String sex) {
if (flag)
try {
this.wait(); //wait等待把线程放到线程池里
} catch (Exception e) {
}
this.name = name;
this.sex = sex;
System.out.println("【SET】" + name + sex);
flag = true;
this.notify();//notify唤醒一个,一般最先唤醒最早wait进线程池的
//notifyAll();唤醒全部
}
public synchronized void out() {
if (!flag)
try {
this.wait();
} catch (Exception e) {
}
System.out.println("【OUT】" + name + sex);
flag = false;
this.notify();
}
}
class Input implements Runnable {
private Res r;
Input(Res r) {
this.r = r;
}
public void run() {
int x = 1;
while (x < 6) {
r.set("丽丽" + x, "女");
x++;
}
}
}
class Output implements Runnable {
private Res r;
Output(Res r) {
this.r = r;
}
public void run() {
while (true) {
r.out();
}
}
}
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-55883-5.html
哈哈
泻做尸叫兽