Java多線程列印數字

來源:互聯網
上載者:User

問題:從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 等基本類型上


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.