/** * 方案一 * * @author LY */ public class LockObject { public String lockName; public LockObject() { } public LockObject(String lockName) { this.lockName = lockName; } public String getLockName() { return lockName; } public void setLockName(String lockName) { this.lockName = lockName; } } public class MyThread implements Runnable { private String name; private String next; private LockObject lock; MyThread(String name, String next, LockObject lock) { this.name = name; this.next = next; this.lock = lock; } /** * 三个线程同时启动: * 1.new Thread(new MyThread("A", "B", data)).start(); * 2.new Thread(new MyThread("B", "C", data)).start(); * 3.new Thread(new MyThread("C", "A", data)).start(); * 同时进入循环: * 前面Data data = new Data("A"); * 所以data=A * 第一个线程满足条件,进入同步方法:打印A,设置data=B,count=2 * 第二个线程不满足条件,进入无限循环,count=3 * 第三个线程不满足条件,进入无限循环,count=3 * data=B * 第二个线程满足条件,进入同步方法:打印B,设置data=C,count=2 * 第一个线程不满足条件,进入无限循环,count=2 * 第三个线程不满足条件,进入无限循环,count=3 * data=C * 第三个线程满足条件,进入同步方法:打印C,设置data=A,count=2 * 第一个线程不满足条件,进入无限循环,count=2 * 第二个线程不满足条件,进入无限循环,count=2 * * 当再次data=A * 从第一个线程开始,三个线程依次符合条件再跑一次,count=1 * * 打印结果:ABCABCABC */ public void run() { int count = 3; while (count > 0) { if (lock.getLockName().equals(name)){ synchronized (lock) { System.out.print(name); lock.setLockName(next); count--; } } } } public static void main(String[] args) throws InterruptedException { LockObject data = new LockObject("A"); new Thread(new MyThread("A", "B", data)).start(); new Thread(new MyThread("B", "C", data)).start(); new Thread(new MyThread("C", "A", data)).start(); } }
/** * 方案二 * * @author LY */ public class MyThread implements Runnable { private String name; private MyThread myThread; public MyThread() {} public MyThread(String name) { this.name = name; } public void setMyThread(MyThread myThread) { this.myThread = myThread; } public void run() { int count = 0; try { while (count < 3) { synchronized (myThread) { synchronized (this) { System.out.print(name); count++; this.notify(); } myThread.wait(); } } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws InterruptedException { MyThread a = new MyThread("A"); MyThread b = new MyThread("B"); MyThread c = new MyThread("C"); a.setMyThread(c); b.setMyThread(a); c.setMyThread(b); new Thread(a).start(); Thread.sleep(10); new Thread(b).start(); Thread.sleep(10); new Thread(c).start(); Thread.sleep(10); } }