我正在运行下面的程序,但由于某种原因,它看起来不像我正在使用 run() 方法。基本上我试图发现线程的行为。我得到以下结果:
pqni392fr8dchsdmajglvuqsof
pqni392fr8dchsdmajglvuqsof has wake up
l79uho1tjtot7pcmk4vhh5t8qc
l79uho1tjtot7pcmk4vhh5t8qc has wake up
adfapus6g1fst56daimrudkgji
adfapus6g1fst56daimrudkgji has wake up
iqfo9knc99kcb622g36c77m62
iqfo9knc99kcb622g36c77m62 has wake up
67vdpghqit1a4iv3593451ps0a
67vdpghqit1a4iv3593451ps0a has wake up
如您所见,我没有进入线程应该休眠的 run() 方法。有什么问题?还有一个问题,线程是否可以从程序的第一次运行开始执行 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();
}
}