刚学线程 想实现简单的生产消费程序:pppppppppppppppppppp
cccccccccccccccccccc
pppppppppppppppppppp
cccccccccccccccccccc
...p是生产一次, c是消费一次代码如下
class Food{
static boolean flag = true; // 设 true 需要生产
public synchronized void proFood(){
if(!flag){
try{
super.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("pppppppppp");
flag = false;
super.notify();
} public synchronized void conFood(){
if(flag){
try{
super.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
try{
Thread.sleep(1);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("ccccccccc");
flag = true;
super.notify();
}
}class Producer implements Runnable{
Food f = new Food();
public static int howMany;
Producer(int howMany){
this.howMany = howMany;
}
public void run(){
for(int i = 0; i < howMany; i++){
f.proFood();
}
}
}class Consumer implements Runnable{
Food f = new Food();
public void run(){
for(int i = 0; i < Producer.howMany; i++){
f.conFood();
}
}
}
public class Test {
public static void main(String args[]) throws Exception{
Producer p = new Producer(10);
Consumer c = new Consumer();
new Thread(p).start();
new Thread(c).start();
}
}结果只输出了一行pppppppppppppp 就停住了,程序没有结束,好像哪里死锁了 ???
cccccccccccccccccccc
pppppppppppppppppppp
cccccccccccccccccccc
...p是生产一次, c是消费一次代码如下
class Food{
static boolean flag = true; // 设 true 需要生产
public synchronized void proFood(){
if(!flag){
try{
super.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("pppppppppp");
flag = false;
super.notify();
} public synchronized void conFood(){
if(flag){
try{
super.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
try{
Thread.sleep(1);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("ccccccccc");
flag = true;
super.notify();
}
}class Producer implements Runnable{
Food f = new Food();
public static int howMany;
Producer(int howMany){
this.howMany = howMany;
}
public void run(){
for(int i = 0; i < howMany; i++){
f.proFood();
}
}
}class Consumer implements Runnable{
Food f = new Food();
public void run(){
for(int i = 0; i < Producer.howMany; i++){
f.conFood();
}
}
}
public class Test {
public static void main(String args[]) throws Exception{
Producer p = new Producer(10);
Consumer c = new Consumer();
new Thread(p).start();
new Thread(c).start();
}
}结果只输出了一行pppppppppppppp 就停住了,程序没有结束,好像哪里死锁了 ???
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货