黑马程序员技术交流社区
标题:
为什么老是锁死呢
[打印本页]
作者:
小洋人最happy
时间:
2012-12-9 16:21
标题:
为什么老是锁死呢
/*
第十二天 多线程
01 线程间通信(示例代码) 02 解决安全问题
无论是售票还是存钱的例子,开启的线程所运行的代码是一致的。
拉煤的例子,一个送,一个拉,同时进行的。动作不一致,运行代码不一致。
所以要有两个run方法来存放数据,放在两个类中。
线程间通讯:就是多个线程操作同一个资源,但是操作的动作不同。
*/
class Rec
{
String name;
String sex;
}
class Input implements Runnable
{
Rec r;
Input(Rec r)
{
this.r = r;
}
public void run()
{
int x =0;
while (true)
{
synchronized(r)
{
if(x==0)
{
r.name = "mike";
r.sex = "man";
}
else
{
r.name = "丽丽";
r.sex = "女女女女女";
}
x = (x+1)%2;
}
}
}
}
class Output implements Runnable
{
Rec r;
Output(Rec r)
{
this.r = r;
}
public void run()
{
synchronized(r)
{
System.out.println(r.name+"::::"+r.sex);
}
}
}
class ThreadDemo1
{
public static void main(String[] args)
{
Rec r = new Rec();
Input in = new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
作者:
Rancho_Gump
时间:
2012-12-9 17:38
本帖最后由 张向辉 于 2012-12-9 17:42 编辑
class Rec
{
String name;
String sex;
}
class Input implements Runnable
{
Rec r;
Input(Rec r)
{
this.r = r;
}
public void run()
{
int x =0;
while (true)//老师为了演示,这里用了死循环。。。。。
{
synchronized(r)
{
if(x==0)
{
r.name = "mike";
r.sex = "man";
}
else
{
r.name = "丽丽";
r.sex = "女女女女女";
}
x = (x+1)%2;
}
}
}
}
class Output implements Runnable
{
Rec r;
Output(Rec r)
{
this.r = r;
}
public void run()
{
while(true)//你这里少了这句所以,就打印了一句而已。程序是死循环,而不是死锁!
{ synchronized(r)
{
System.out.println(r.name+"::::"+r.sex);
}
}
}
}
class ThreadDemo1
{
public static void main(String[] args)
{
Rec r = new Rec();
Input in = new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
-----------------------------------------------------
你的程序只输出了一句,程序不动了是因为while(true)造成的死循环,而不是死锁,这个程序没有死锁问题!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2