您的位置:首页 > 大数据 > 人工智能

使用Thread的wait和notify方法实现线程通信

2014-05-28 12:37 477 查看
package thread1;
/**
* 线程通信例子(基于线程wait,notify)
* */
public class PC {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Q q = new Q();
new Producer(q);
new Customer(q);
//System.out.println("Press Control-C to stop.");
}
}
/**
* 阻塞队列
* */
class Q{
int n;
boolean valueSet = false;
@SuppressWarnings("static-access")
synchronized int get(){
//值未设置好,循环等待
while(!valueSet){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//取值成功
System.out.println("Got:"+n);
//将设置标志置为false
valueSet = false;
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//通知设值线程
this.notify();
return n;
}
@SuppressWarnings("static-access")
synchronized void put(int n){
//已经设置好了值,而且未被取走,循环等待
while(valueSet){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.n = n;
//将设置标志设置为true
valueSet = true;
System.out.println("Put:"+n);
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//通知取值线程,可以取值
this.notify();
}
}
/**
* 生产者
* */
class Producer implements Runnable{
Q q;
public Producer(Q q){
this.q = q;
new Thread(this,"Producer").start();
}
@Override
public void run() {
// TODO Auto-generated method stub
int i=0;
while(true){
q.put(i++);
}
}
}
/**
* 消费者
* */
class Customer implements Runnable{
Q q;
public Customer(Q q){
this.q=q;
new Thread(this,"Customer").start();
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
q.get();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: