首页 > 编程语言 > 详细

多线程操作的同步问题

时间:2014-03-15 21:17:32      阅读:415      评论:0      收藏:0      [点我收藏+]


class Res
{
private String name;
private String sex;
private 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;
Input(Res r)
{
this.r =r;
}
public void run()
{
int x = 0;
while(true)
{
if(x==0)
r.set("mike","man");
else
r.set("lili","girl");
x =(x+1)%2;

}

}

}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r = r;

}
public void run()
{
while(true)
{
r.out();
}
}

}
class MultThreadDemo2
{
public static void main(String[] args)
{
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}

多线程操作的同步问题,布布扣,bubuko.com

多线程操作的同步问题

原文:http://www.cnblogs.com/wilson0824/p/3602186.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!