我正在运行下面的程序,但由于某种原因,它看起来不像我正在运行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