class Ticket implements Runnable { private static int tick = 100; boolean flag = true; @Override public void run() { if (flag) { while (true) { synchr ...
class Ticket implements Runnable { private static int tick = 100; boolean flag = true; @Override public void run() { if (flag) { while (true) { synchronized (Integer.class) { show(); } } } else while (true) show(); } public synchronized void show() { synchronized (Integer.class) { if (tick > 0) { try { Thread.sleep(10); } catch (InterruptedException e) { } System.out.println(Thread.currentThread().getName() + "...show():" + tick--); } } } } public class Demo { public static void main(String[] args) { Ticket t = new Ticket(); Thread t1 = new Thread(t); Thread t2 = new Thread(t); t1.start(); try { Thread.sleep(10); } catch (InterruptedException e) { } t.flag = false; t2.start(); } }
同步中嵌套同步。
寫一個死鎖:
class Test implements Runnable { private boolean flag; Test(boolean flag) { this.flag = flag; } @Override public void run() { if (flag) { while (true) { synchronized (Object.class) { System.out.println("if Object..."); synchronized (Integer.class) { System.out.println("if Integer..."); } } } } else { while (true) { synchronized (Integer.class) { System.out.println("else Integer..."); synchronized (Object.class) { System.out.println("else Object..."); } } } } } } public class DeadLockDemo { public static void main(String[] args) { Thread thread1 = new Thread(new Test(true)); Thread thread2 = new Thread(new Test(false)); thread1.start(); thread2.start(); } }