黑马程序员技术交流社区
标题:
多线程疑问
[打印本页]
作者:
EDDY_Liang
时间:
2014-9-28 12:38
标题:
多线程疑问
本帖最后由 EDDY_Liang 于 2014-9-28 14:26 编辑
为什么我试了很多次就是不出来统一数字生产多次或消费多次的情况啊??是因为cpu是双核的缘故吗??
视频里说是会出问题的。。。。
朋友们看一下谢谢!
public class Produce$CustomerDemo {
public static void main(String[] args) {
Resource s = new Resource("烤鸭");
Producer p = new Producer(s);
Consumer c = new Consumer(s);
Thread t1 = new Thread(p);
Thread t3 = new Thread(p);
Thread t2 = new Thread(c);
Thread t4 = new Thread(c);
t1.start();
t3.start();
t2.start();
t4.start();
}
}
class Resource {
String thing;
Resource(String thing) {
this.thing = thing;
}
boolean flag = false;
int count = 1;
public void set() {
while (true)
synchronized (this) {
if (!flag) {
System.out.println(thing + ".....生产" + count);
flag = true;
}
}
}
public void out() {
while (true)
synchronized (this) {
if (flag) {
System.out.println(thing + "..............消费" + count++);
flag = false;
}
}
}
}
class Producer implements Runnable {
private Resource R;
Producer(Resource R) {
this.R = R;
}
@Override
public void run() {
R.set();
}
}
class Consumer implements Runnable {
private Resource R;
Consumer(Resource R) {
this.R = R;
}
@Override
public void run() {
R.out();
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2