- 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的方式给需要同步的代码加上了锁,为什么还是会出现安全性的问题呢 |
|