1. 多个线程在操作同一份资源时,其操作如果一致的,则不需要使用线程之间的通信,如多个线程卖票。如果操作不一致,则可能需要线程通信。
2. java中线程之间的通信一般利用wait和notify方法来实现的
2.1 wait(),wait()方法使得当前线程必须要等待,等到另外一个线程调用notify()或者notifyAll()方法。当前的线程必须拥有当前对象的monitor,也即lock,就是锁。线程调用wait()方法,释放它对锁的拥有权,然后等待另外的线程来通知它(通知的方式是notify()或者notifyAll()方法),这样它才能重新获得锁的拥有权和恢复执行。要确保调用wait()方法的时候拥有锁,即,wait()方法的调用必须放在synchronized方法或synchronized块中。注意:sleep方法不会释放锁,而wait会释放锁。
2.2 notify方法,该方法同样只能被当前的锁所调用,即只能在同步中使用。调用之后会会唤醒阻塞线程池中的线程的某一个,一般为第一个。唤醒之后并不是立即执行,而是和其他的线程一起参加竞争。
lass Resource{
private int count=0;
private boolean flag=false;
//定义生产资源
public synchronized void produce(){
while(flag)
try{this.wait();}catch(Exception e){};
System.out.println(Thread.currentThread().getName()+"...生产..."+count++);
flag=true;
//this.notify();
this.notifyAll();
}
//定义消费
public synchronized void consume(){
while(!flag)
try{this.wait();}catch(Exception e){};
System.out.println(Thread.currentThread().getName()+".......消费..."+count);
flag=false;
//this.notify();
this.notifyAll();
}
}
class Produce implements Runnable{
Resource res;
//定义共享资源
public Produce(Resource res){
this.res=res;
}
public void run(){
while(true){
res.produce();
}
}
}
class Consume implements Runnable{
Resource res;
public Consume(Resource res){
this.res=res;
}
public void run(){
while(true){
res.consume();
}
}
}
public class app {
public static void main(String[] args) {
Resource res=new Resource();
Consume con=new Consume(res);
Produce pro=new Produce(res);
new Thread(pro).start();
new Thread(pro).start();
new Thread(con).start();
new Thread(con).start();
}}