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.name = "zhangsan";
try{Thread.sleep(1);}catch(Exception e){}
q.sex = "male";
}
else
{
q.name = "lisi";
q.sex = "female";
}
i = (i + 1)%2;
}
}
}
class Consumer implements Runnable
{
Q q;
public Consumer(Q q)
{
this.q = q;
}
public void run()
{
while(true)
{
System.out.println("name of q: " + q.name);
System.out.println("Gender of q: " + q.sex);
}
}
}
class Q
{
String name = "unknown";
String sex = "unknow";
}
class ThreadCommunation
{
public static void main(String[] args)
{
Q q = new Q();
Thread producer = new Producer(q);
producer.start();
Thread consumer = new Consumer(q);
consumer.start();
}
}
线程同步 生产者消费者
最新推荐文章于 2024-07-15 22:27:18 发布