class Producer implements Runnable
{
Q q;
public Producer(Q q)
{
this.q = q;
}
public void run()
{
int i = 0;
while (true)
{
if (i == 0)
{
q.put("zhangsan","male");
}
else
{
q.put("lisi","female");
}
i = (i+1)%2;
}
}
}
class Consumer implements Runnable
{
Q q;
public Consumer(Q q)
{
this.q = q;
}
public void run()
{
while (true)
{
q.get();
}
}
}
class Q
{
private String name;
private String sex;
boolean bFull = false;
public synchronized void put(String name , String sex)
{
if (bFull)
{
try{wait();}catch(Exception e){}
}
this.name = name;
this.sex = sex;
bFull = true;
notify();
}
public synchronized void get()
{
if (!bFull)
{
try{wait();}catch(Exception e){}
}
System.out.print(name);
System.out.println(sex);
bFull = false;
notify();
}
}
class ThreadComunication
{
public static void main(String[] args)
{
Q q = new Q();
new Thread(new Producer(q)).start();
new Thread(new Consumer(q)).start();
}
}
Consumer 和 Producer 的线程同步和通信
最新推荐文章于 2021-10-10 21:00:00 发布