1 public class ThreadDemo { 2 public static void main(String[] args) { 3 ThreadTest test = new ThreadTest(); 4 new Thread(test).start(); 5 new Thread(test).start(); 6 new Thread(test).start(); 7 new Thread(test).start(); 8 } 9 } 10 11 class ThreadTest implements Runnable { 12 private volatile int count = 10; 13 14 public void run() { 15 16 while (count > 0) { 17 synchronized (this) { 18 System.out.println(Thread.currentThread().getName() + " " 19 + count--); 20 } 21 } 22 23 } 24 }
Thread-0 10
Thread-3 9
Thread-3 8
Thread-3 7
Thread-3 6
Thread-3 5
Thread-3 4
Thread-3 3
Thread-3 2
Thread-3 1
Thread-2 0
Thread-1 -1
Thread-0 -2
修正案:
1 public class ThreadDemo { 2 public static void main(String[] args) { 3 ThreadTest test = new ThreadTest(); 4 new Thread(test).start(); 5 new Thread(test).start(); 6 new Thread(test).start(); 7 new Thread(test).start(); 8 } 9 } 10 11 class ThreadTest implements Runnable { 12 private volatile int count = 10; 13 14 public void run() { 15 16 while (count > 0) { 17 synchronized (this) { 18 if (count > 0) { 19 System.out.println(Thread.currentThread().getName() + " " 20 + count--); 21 } 22 } 23 } 24 25 } 26 }
Thread-0 10
Thread-1 9
Thread-1 8
Thread-1 7
Thread-1 6
Thread-0 5
Thread-0 4
Thread-0 3
Thread-0 2
Thread-0 1