簡體   English   中英

為什么我的Java多線程代碼無法正常工作?

[英]Why my Java multithreading code does not work properly?

確實需要您的幫助才能弄清楚發生了什么。 該代碼看似微不足道,但會產生錯誤的輸出。

這是一個基本的生產者-消費者問題。 生成器線程生成質數,並且使用者(acceptors)必須對其進行處理。 在App中,我創建了兩個接受器和1個生成器線程。 問題是我得到以下輸出為50:

Thread Thread-2 puts 47
Thread Thread-2 puts 43
Thread Rob gets 47
Thread Rob gets 43
Thread Thread-1 gets 47
Thread Nick puts 47
etc...

我不知道為什么要打印Thread-2和Thread-1 ...這些線程來自哪里? 謝謝

public class PrimeGenerator implements Runnable{
    private PrimeCentral primeCentral;
    int bound;

    public PrimeGenerator(PrimeCentral PC, int bound){
        this.primeCentral = PC;
        this.bound = bound;
        new Thread(this).start();
    }

    @Override
    public void run() {
          int n=bound;
          while (n > 1) {
             int d;
             for (d=2; d <= n/2; d++) 
                if ((n % d) == 0) break; 
             if (d > n/2) {
                 primeCentral.put(n);
                System.out.println("Thread " + Thread.currentThread().getName() + " puts " + n);
             }
          n--; 
          }

    }

}

public class PrimeCentral {
    private int prime;
    private boolean available = false;


    public synchronized void put(int n){
        while(available == true){
            try{
                wait();
            }catch(InterruptedException e){}
        }
        prime = n;
        available = true;
        notifyAll();        
    }

    public synchronized int get(){
        while(available == false){
            try{
                wait();
            }catch(InterruptedException e){}
        }
        available = false;
        notifyAll();
        return prime;
    }

}
public class PrimeAcceptor implements Runnable{
    private PrimeCentral primeCentral;

    public PrimeAcceptor(PrimeCentral primeCentral){
        this.primeCentral = primeCentral;
        new Thread(this).start();
    }


    public void run() {
          while (true) {
              int prime = primeCentral.get();
              System.out.println("Thread " + Thread.currentThread().getName() + " gets " + prime);
              if (prime == 2) break; 
          }
    }

public class App {

    public static void main(String[] args) {

        PrimeCentral pc = new PrimeCentral();

        new Thread(new PrimeAcceptor(pc), "Bob").start();
        new Thread(new PrimeAcceptor(pc), "Rob").start();

        new Thread(new PrimeGenerator(pc, 50), "Nick").start();

    }
}

編輯:對不起,我被這個愚蠢的錯誤愚弄的人

您正在使用new Thread(this).start().啟動兩個線程new Thread(this).start().

它們都將具有您提到的表單的名稱。

我認為您正在啟動四個線程,而您只打算啟動兩個線程。 在出現的兩個地方都刪除上面的行。

暫無
暫無

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

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