为什么我的多线程程序仍在运行,即使我正在加入?

时间:2015-05-13 18:52:08

标签: java multithreading

我的程序仍在运行,即使我正在为主要的每个线程进行连接。 同样很明显我的线程方法没有任何infitite循环。那可能是什么原因?

public static void main(String[] args) throws InterruptedException{

    PrimeCentral pc = new PrimeCentral();

    Thread one = new Thread(new PrimeAcceptor(pc), "Acceptor1");
    Thread two = new Thread(new PrimeAcceptor(pc), "Acceptor2");
    Thread three = new Thread(new PrimeGenerator(pc, 50), "Generator");
    one.start();
    two.start();
    three.start();

    one.join();
    two.join();
    three.join();
}

第一个线程运行方法

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--; 
      }

}

第二个Thread类运行方法

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

}

Prime Central

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


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

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

}

控制台输出:

Thread Acceptor2 gets 47
Thread Generator puts 47
Thread Generator puts 43
Thread Acceptor2 gets 43
Thread Generator puts 41
Thread Acceptor1 gets 41
Thread Acceptor2 gets 37
Thread Generator puts 37
Thread Generator puts 31
Thread Generator puts 29
Thread Generator puts 23
Thread Acceptor2 gets 31
Thread Acceptor2 gets 23
Thread Acceptor2 gets 19
Thread Acceptor1 gets 29
Thread Generator puts 19
Thread Generator puts 17
Thread Acceptor1 gets 17
Thread Acceptor2 gets 13
Thread Generator puts 13
Thread Generator puts 11
Thread Acceptor2 gets 11
Thread Acceptor1 gets 7
Thread Generator puts 7
Thread Acceptor1 gets 5
Thread Generator puts 5
Thread Generator puts 3
Thread Acceptor1 gets 3
Thread Acceptor2 gets 2
Thread Generator puts 2

1 个答案:

答案 0 :(得分:0)

那是因为join只是为了完成另一个线程而创建了一个线程。因此,如果您调用one.join,则会使其他线程等待one的完成。您只是按顺序执行线程。

您希望程序的行为恰恰是什么?