本帖最后由 黄克帅 于 2012-5-29 17:44 编辑
比老师视频上面讲的是 当true的时候 生产者就等待 ,当false的时候,消费者就等待。这样需要等待唤醒进行切换。 我改了下逻辑 改成当false的时候 生产者就生产 ,当true的时候 消费者就消费。 这样我不需要等待 唤醒切换,且不用while循环判断标签 貌似也可以实现功能,只是效率低点。 大家帮忙看看 代码有问题没。
毕老师原代码:
public class Resource {
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name) {
while (flag==true) {//每次唤醒都判断标签
try {
wait();//为true时 进入冻结状态 释放执行权
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name + "---" + count++;
System.out.println(Thread.currentThread().getName() + "...生产者。。。"
+ this.name);
flag = true;
this.notifyAll();//唤醒所有线程
}
public synchronized void out() {
while (flag==false) {//每次唤醒都判断标签
try {
wait();//为false时 进入冻结状态 释放执行权
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "...消费者。。。..."
+ this.name);
flag = false;
this.notifyAll();//唤醒所有线程
}
}
修改后代码
public class Resource {
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name) {
if(flag == false) {// 为false时生产
this.name = name + "---" + count++;
System.out.println(Thread.currentThread().getName() + "...生产者。。。"
+ this.name);
flag = true;
}
}
public synchronized void out() {
if(flag == true) {// 为true时消费
System.out.println(Thread.currentThread().getName()
+ "...消费者。。。..." + this.name);
flag = false;
}
}
}
以下不变
public class Prodoucer implements Runnable {
private Resource res;
public Prodoucer(Resource res) {
this.res = res;
}
public void run() {
while(true){
res.set("+商品+");
}
}
}
public class Consumer implements Runnable {
private Resource res;
public Consumer(Resource res) {
this.res = res;
}
public void run() {
while(true){
res.out();
}
}
}
public class Test {
public static void main(String[] args) {
Resource r = new Resource();
Prodoucer pro = new Prodoucer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(con);
Thread t3 = new Thread(pro);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
} |