簡體   English   中英

Java中的線程同步/生產者-消費者。 重復打印數字1-10,然后再打印10-1

[英]Thread synchronization/producer-consumer in java. Printing out numbers 1-10 then 10-1 repeatedly

我對Java非常陌生,並且發現了一個可以進行基本線程同步的練習。 問題是反復打印出12345678910 10987654321,直到程序停止。 應該使用十個不同的線程。

到目前為止,這是我的代碼:我正在首先嘗試僅獲取第一個數字(起作用的數字),但是它一直給我一個例外

public static void main(String[] args){
   threadOne one = new threadOne();
   one.start();
    }
}

class updateNumber{
    private int i;
    synchronized void increase(int s){
        this.i=s;
        System.out.println(i);
    }
 } 

class threadOne extends Thread {
    private updateNumber grab;
     public void run() {
        try{
         grab.increase(1);
        }
        catch(Exception e){
         System.out.println("error in thread one");
        }
    }
}

我可能會以完全錯誤的方式進行此操作,但是我已經閱讀了很多文檔,並且感到非常困惑。

看來您沒有創建更新的新實例

class threadOne extends Thread {
    private updateNumber grab;
     public void run() {
        try{
         grab.increase(1); // null pointer reference...<<<<<<<
        }
        catch(Exception e){
         System.out.println("error in thread one");
        }
    }
}

//您需要像這樣將內存分配給updateNumber

//private updateNumber grab = new updateNumber();

    class threadOne extends Thread {
        private updateNumber grab = new updateNumber(); 
         public void run() {
            try{
             grab.increase(1); 
            }
            catch(Exception e){
             System.out.println("error in thread one");
            }
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM