問題:從0列印到99
約束:有三個線程 A、B、C,其中A列印0~4,B列印5~9,C列印10~14,然後A列印15到19,B列印20~24,以此類推
首先,寫了一塊代碼,如下
public class PrintThread extends Thread {private int id;private static Integer n = 0;public PrintThread(int id) {this.id = id;}@Overridepublic void run() {while (n < 100) {synchronized (n) {while ((n % 5 != 0) || (n % 5 == 0 && (n / 5) % 3 != id)) {try {n.wait();} catch (InterruptedException e) {e.printStackTrace();}}if (n < 100) {System.out.print("Thread-" + id + " : " + n + " " + (n + 1)+ " " + (n + 2) + " " + (n + 3) + " " + (n + 4)+ "\n");n += 5;}n.notifyAll();}}}public static void main(String[] args) {Thread t0 = new PrintThread(0);Thread t1 = new PrintThread(1);Thread t2 = new PrintThread(2);t0.start();t1.start();t2.start();}}
,結果發現會出問題,在n.notifyAll() 的時候會報 java.lang.IllegalMonitorStateException 異常
經檢查,發現 n 在 n+=5 之後,已經變成了另一個對象,也就是 n 已經變了
以此類推,其他的基本類型也是這樣,因為 Integer類中 儲存的值為 private final int value;
改成如下的代碼,即可
public class PrintThread extends Thread {private int id;private static Integer n = 0;private static final Object lock = new Object();public PrintThread(int id) {this.id = id;}@Overridepublic void run() {while (n < 100) {synchronized (lock) {while ((n % 5 != 0) || (n % 5 == 0 && (n / 5) % 3 != id)) {try {lock.wait();} catch (InterruptedException e) {e.printStackTrace();}}if (n < 100) {System.out.print("Thread-" + id + " : " + n + " " + (n + 1)+ " " + (n + 2) + " " + (n + 3) + " " + (n + 4)+ "\n");n += 5;}lock.notifyAll();}}}public static void main(String[] args) {Thread t0 = new PrintThread(0);Thread t1 = new PrintThread(1);Thread t2 = new PrintThread(2);t0.start();t1.start();t2.start();}}
這個事件給我們的教訓是,不要把鎖加在 Integer 等基本類型上