多个线程在操作同一个资源,操作动作不同
package 线程通信;
import java.security.interfaces.RSAKey;
import 电话号码.Main;
/*
* 例子:生产者消费者
* 如果两个线程生成,两个线程消费
*/
public class Resource {
private String name;
private int count=1;
private boolean flag=false;//标记
public synchronized void set(String name){
if(flag)
try{
wait();
}catch (Exception e) {
// TODO: handle exception
}
this.name=name+"---"+count++;
System.out.println(Thread.currentThread().getName()+"生产者..."+this.name);
flag=true;
this.notify();
}
public synchronized void out(){
if(!flag){
try {
wait();
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(Thread.currentThread().getName()+"...."+this.name);
flag=false;
this.notify();
}
}
public static void main(String[] args) {
Resource res=new Resource();
Producer pd=new Producer(res);
Consumer cs=new Consumer(res);
Thread t1=new Thread(pd);
Thread t2=new Thread(cs);
t1.start();
t2.start();
}
}
class Producer implements Runnable{
private Resource res;
Producer(Resource res){
this.res=res;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
res.set("+商品+");
}
}
}
class Consumer implements Runnable{
private Resource res;
Consumer(Resource res){
this.res=res;
}
public void run() {
while(true){
res.out();
}
}
}
-----------------------------------------------------
总结:wait() notify() notifyAll()
wait()等待,不占用cpu,将线程放入线程池中
notify()唤醒线程池中第一个等待的线程
notifyAll()唤醒全部线程
wait()会throws InterruptedException
所以只能try处理
上述方法全用在同步中,必须标记锁(当前线程必须拥有此对象锁):this.notify()
对持有监视器(锁)的线程操作,所以要使用在同步中,因为只有同步才具有锁。
为什么操作线程的方法可以定义在Object中?
因为这些方法在操作同步中线程时,都必须要标记它们所操作线程只有的锁,只有
同一个锁上的被等待的线程,可以被同一个锁上的notify唤醒(等待和唤醒必须是同一个锁)
而锁可以是任意对象,所以可以被任意对象调用的方法定义在Object中