3 回答

TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超5個(gè)贊
首先,要?jiǎng)?chuàng)建一個(gè) thead,您將一個(gè) runnable 傳遞給構(gòu)造函數(shù)。您所做的是嘗試將myThread()返回的值傳遞給它,而不是方法引用。
(不要)試試這個(gè):(它可能會(huì)導(dǎo)致系統(tǒng)崩潰,因?yàn)樗鼤?huì)產(chǎn)生無限數(shù)量的線程)
public static void main(String[] args) throws InterruptedException{
System.out.println("start");
new Thread(() -> myThread()).start(); // Added () ->
System.out.println("return");
}
private static void myThread() throws InterruptedException{
System.out.println("start");
Thread.sleep(1000);
new Thread(() -> myThread()).start(); // Added () ->
System.out.println("return");
}
我也讓它返回void,因?yàn)榇藭r(shí)返回 null 毫無意義。
然后,正如所指出的,您需要限制創(chuàng)建的線程數(shù)量。例如,如果你想要兩個(gè)線程:
private static final int numThreads = 0; // added
public static void main(String[] args) throws InterruptedException{
System.out.println("start");
new Thread(() -> myThread()).start();
System.out.println("return");
}
private static void myThread() throws InterruptedException{
System.out.println("start");
Thread.sleep(1000);
if (++numThreads < 2) // added
new Thread(() -> myThread()).start();
System.out.println("return");
}

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超8個(gè)贊
我想在具有相同主體的線程中啟動(dòng)一個(gè)線程。創(chuàng)建新線程后,我想繞過啟動(dòng)新線程的行并運(yùn)行其余代碼。
是這樣的:
public class Test {
public class Worker extends Runnable {
private boolean launchedSubthread = false;
public void run() {
if (!launchedSubthread) {
launchedSubthread = true;
new Thread(this).start();
}
// Now do some stuff.
}
}
public void main(String[] args) {
new Thread(new Worker()).start();
}
}
請(qǐng)注意,當(dāng)我們啟動(dòng)類中的第二個(gè)子線程時(shí)Worker,我們將this作為Runnable. 所以這兩個(gè)子線程將共享一個(gè)Worker實(shí)例作為它們的“主體”。(我假設(shè)這就是你想要做的。)
在你想讓兩個(gè)線程讀取或更新 的其他變量Worker,那么你必須適當(dāng)?shù)厥褂胿olatileor synchronized。這不適用于我使用的方式launchedSubthread。這是因?yàn)樵谡{(diào)用和新啟動(dòng)的線程上的調(diào)用之間發(fā)生了happens before 。start()run()
您的嘗試有幾個(gè)問題。
myThread
被錯(cuò)誤命名。它返回的Runnable
不是Thread
.您沒有做任何事情來阻止
MyThread
實(shí)例的無限鏈創(chuàng)建。您實(shí)際上并沒有創(chuàng)建任何線程。如果仔細(xì)觀察
myThread()
,它會(huì)在創(chuàng)建任何線程之前(無限地)遞歸。myThread()
調(diào)用null
返回。如果它實(shí)際上被傳遞給了Thread(Runnable)
構(gòu)造函數(shù),你就會(huì)得到一個(gè) NPE。

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊
嘗試這個(gè) :
public static void main(String[] args) throws InterruptedException{
System.out.println("start");
new Thread(myThread()).start();
System.out.println("return");
return;
}
static boolean threadStared = false;
private static Runnable myThread() throws InterruptedException{
System.out.println("start");
Thread.sleep(1000);
if(!threadStared){
new Thread(myThread()).start();
threadStared = true;
}
System.out.println("return");
return null;
}
添加回答
舉報(bào)