我想开始10个线程。主线程启动第一个线程,第一个线程启动第二个,依此类推,最多10个,但不是10个线程创建了19个线程

时间:2017-02-01 12:55:15

标签: java multithreading

package testpkg;

public class ThreadOrdering {
    public static void main(String[] args) {
        MyRunnable[] threads = new MyRunnable[10];//index 0 represents thread 1;
        for(int i=0; i < 10; i++)
            threads[i] = new MyRunnable(i, threads);
        //threads[0] = new MyRunnable(0, threads);
        new Thread(threads[0]).start();  
     }

}

class MyRunnable implements Runnable {
    int threadNumber;
    MyRunnable[] threads;

    public MyRunnable(int threadNumber, MyRunnable[] threads) {
        this.threadNumber = threadNumber;
        this.threads = threads;
    }

    public void run() {
    synchronized (this) {
        if(this.threadNumber!=10)
            new Thread(threads[this.threadNumber]).start();
            this.threadNumber++;
    }
    System.out.println("the thread " + Thread.currentThread().getName() + " with num " + this.threadNumber);
}

}

我实际上不应该增加threadNumber,但如果我不这样做会进入无限循环,如果我增加了19个线程而不是10个

1 个答案:

答案 0 :(得分:2)

导致重复线程启动的threadNumber++。 如果您使用new Thread(threads[this.threadNumber+1]).start();(并删除threadNumber++),则只会启动10个。

让我们检查逻辑:

new Thread(threads[0]).start();  // Start the first thread

// Inside the first thread's run
if(0 != 10)
    new Thread(threads[0]).start(); // Oh noes, we restarted the first thread/runnable
this.threadNumber++; // We restarted the thread, AND incremented its threadnumber!

// Inside the first runnable's run AGAIN!
if(1 != 10)
    new Thread(threads[1]).start(); // NOW we started the second thread
this.threadNumber++; // First thread's threadnumber is now 2, but we didn't restart it so it won't run again

因此除了最后一个(10 != 10返回false)之外的每个线程都会重启一次,总共有19个线程。