我正在運行下面的程序,但由於某種原因,它看起來不像我正在運行run()方法。基本上我試圖發現的threads.I我得到的結果如下行爲:
Java中的線程行爲
pqni392fr8dchsdmajglvuqsof
pqni392fr8dchsdmajglvuqsof有醒來
l79uho1tjtot7pcmk4vhh5t8qc
l79uho1tjtot7pcmk4vhh5t8qc有醒來
adfapus6g1fst56daimrudkgji
adfapus6g1fst56daimrudkgji已經醒來
iqfo9knc99kcb622g36c77m62
iqfo9knc99kcb622g36c77m62已醒來
67vdpghqit1a 4iv3593451ps0a
67vdpghqit1a4iv3593451ps0a有醒來
正如你看到的,我沒有得到的run()方法,其中一個線程應該sleep.what是什麼問題? 另一個問題是,線程是否可以從程序的第一次運行中執行run(),因爲我注意到輸出的第一行始終來自main()。
謝謝。
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
class myThread implements Runnable {
@Override// method run is to be executed by a new thread
public void run() {
System.out.println("I am here");
int timeRandom = new Random().nextInt(50);
try {
String ThrName = Thread.currentThread().getName();
Thread.sleep(timeRandom);
System.out.println("Thread " + ThrName + " sleeping " + timeRandom);
} catch (InterruptedException ex) {
Logger.getLogger(myThread.class.getName()).log(Level.SEVERE, null, ex);
}
// throw new UnsupportedOperationException("Not supported yet.");
}
}
class myClass {
static int nthread = 5;
public static void main(String[] args) {
ExecutorService myService = Executors.newFixedThreadPool(nthread);
while (nthread != 0) {
Thread.currentThread().setName(new BigInteger(130, new SecureRandom()).toString(32));
System.out.println(Thread.currentThread().getName());
myService.submit(Thread.currentThread());
System.out.println(Thread.currentThread().getName() + " has wake up");
//
nthread -= 1;
}
myService.shutdown();
}
}
已經** **被喚醒了 – qdii
當我這樣做,我正在運行,並不是說我已經爲設置一個名稱的一個匿名的線程。你得到像「線程池1線程5睡8」的東西? – user1207965
@ user1207965你更改同一個線程的名字,一個你正在運行... – MadProgrammer