`
小菌子
  • 浏览: 21437 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

线程同步 生产者消费者

阅读更多
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();
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics