线程间通信问题的解决:
-- wait:告诉当前线程放弃监视器并进入睡眠状态,直到其它线程进入一同监视器并且调用notify为止。
--notify:唤醒同一对象监视器中调用wait的第一个线程,这类似排队买票,一个人买完后,后面的人才可以买。
-- wait:告诉当前线程放弃监视器并进入睡眠状态,直到其它线程进入一同监视器并且调用notify为止。
--notify:唤醒同一对象监视器中调用wait的第一个线程,这类似排队买票,一个人买完后,后面的人才可以买。
--notifyAll:唤醒同一对象监视器中调用wait的所有线程,具有最高级别的线程首先被唤醒并执行。
package xiancheng;
//synchronized的使用保证了线程间通信的同步
class P{
String name = "李四";
String sex = "女";
boolean bFull = false;//取走数据位false,放入数据为true。
public synchronized void set(String name,String sex){
if(bFull){
try{
wait();
}catch(InterruptedException x){}
}
this.name = name;
try{
Thread.sleep(10);
}catch(Exception e){
System.out.println(e.getMessage());
}
this.sex = sex;
bFull = true;
notify();
}
public synchronized void get(){
if(!bFull){
try{
wait();
}catch(InterruptedException x){}
}
System.out.println(this.name+"---->"+this.sex);
bFull = false;
notify();
}
}
class Producer implements Runnable{
P q = null;
public Producer(P q){
this.q = q;
}
public void run(){
int i = 0;
while(true){
if(i==0){
q.set("张三", "男");
}else{
q.set("李四", "女");
}
i = (i+1)%2;
}
}
}
class Customer implements Runnable{
P q = null;
public Customer(P q){
this.q = q;
}
public void run(){
while(true){
q.get();
}
}
}
public class ThreadCommunation {
public static void main(String[] args) {
P q = new P();
new Thread(new Producer(q)).start();
new Thread(new Customer(q)).start();
}
}