| 发表于:2008-01-24 20:06:21 楼主 |
我做了个线程类不知道加了synchronized就不循环啦。不加它的时候是可以循环的。各位给帮忙看下。下面是程序。 class producer implements runnable { input p=null; public producer(input p) { this.p=p; } public void run() { int i=0; while(true) { synchronized(p) { if(i==0) { p.name="张孝祥"; try { thread.sleep(10); } catch(exception e) { system.out.println(e.getmessage()); } p.sex="男"; } else { p.name="张柏芝"; p.sex="女"; } } i=(i+1)%2; } } } class input { string name=""; string sex=""; } class consumer implements runnable { input p=null; public consumer(input p) { this.p=p; } public void run() { while(true) { synchronized(p) {system.out.println(p.name+"--------> "+p.sex);} } } } public class threadcommunation { /** * @param args */ public static void main(string[] args) { // todo auto-generated method stub input p=new input(); /*producer t1=new producer(p); thread tt1=new thread(t1); tt1.start(); consumer t2=new consumer(p); thread tt2=new thread(t2); tt2.start();*/ new thread(new producer(p)).start(); new thread(new consumer(p)).start(); } } |
|
|
|
|