java 线程间通信同步代码块

import java.lang.*;
class Res
{
	String name;
	String sex;
	boolean flag=false;
	public synchronized void set(String name,String sex)
    {
		if(flag)
		 try
		 {
			this.wait();
		 }
		 catch (Exception e)
		 {
		 }
		this.name=name;
		this.sex=sex;
		flag=true;
		this.notify();
	}
	public synchronized void out()
	{
		if(!flag)
		 try
		 {
			this.wait();
		 }
		 catch (Exception e)
		 {
		 }
		System.out.println(name+"----"+sex);
		flag=false;
		this.notify();
	}

}
class Input implements Runnable
{
	private Res r;
	public Input(Res r)
	{
		this.r=r;
	}
	public void run()
	{
		int x=0;

		while(true)
		{
          if(x==0)
               r.set("lkb","manan");
			else
               r.set("呵呵","你猜");
			x=(x+1)%2;
		}
	}
}

class Output implements Runnable
{
    private Res r;
	public Output(Res r)
	{
		this.r=r;
	}
	public void run()
	{
		while(true)
		{
			r.out();
		}
	}
}
class InputOutput2 
{
	public static void main(String[] args) 
	{
	Res r=new Res();
	new Thread(new Input(r)).start();
	new Thread(new Output(r)).start();
	}
}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lkbsbird/article/details/52373038
文章标签: java
个人分类: Java-基础
上一篇指针复习之单链表实现
下一篇个人学习的链接
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭