黑马程序员技术交流社区
标题:
关于同步锁的一些疑问
[打印本页]
作者:
didixyy
时间:
2015-10-13 15:17
标题:
关于同步锁的一些疑问
import java.util.concurrent.locks.ReentrantLock;
class Res
{
String name, sex;
}
class Input implements Runnable
{
private Res r;
private final ReentrantLock lock = new ReentrantLock();
Input(Res r)
{
this.r = r;
}
public void run()
{
int x = 0;
while (true)
{
lock.lock();
try
{
if (x == 0)
{
r.name = "张三";
r.sex = "男";
} else
{
r.name = "zhan";
r.sex = "nv";
}
}
finally
{
x = (x + 1) % 2;
lock.unlock();
}
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r = r;
}
public void run()
{
while (true)
{
System.out.println(r.name + " " + r.sex);
}
}
}
public class ThreadTel
{
public static void main(String[] args)
{
Res r = new Res();
Input in = new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
复制代码
已经通过LOCK UNLOCK的方式给需要同步的代码加上了锁,为什么还是会出现安全性的问题呢
作者:
didixyy
时间:
2015-10-13 15:21
OutPut里面也加上了同步锁也还是不行
class Output implements Runnable
{
private Res r;
private final ReentrantLock lock = new ReentrantLock();
Output(Res r)
{
this.r = r;
}
public void run()
{
while (true)
{
lock.lock();
try
{
System.out.println(r.name + " " + r.sex);
}
finally
{
lock.unlock();
}
}
}
}
复制代码
作者:
Tangjw
时间:
2015-10-13 15:22
Gender也是性别的意思 , sex好像用着不是很
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2