-1

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

2 回答 2

3

你永远不会将一个实例传递myThread给你的 ExecutorService,而是你正在执行与当前线程相关的所有事情。

你的代码:

Thread.currentThread().setName(new BigInteger(130, new SecureRandom()).toString(32));
System.out.println(Thread.currentThread().getName());
myService.submit(Thread.currentThread());

创建预期结果的代码:

Thread myThread = new Thread(new myThread());
myThread.setName(new BigInteger(130, new SecureRandom()).toString(32));
System.out.println(myThread.getName());
myService.submit(myThread);

另外,作为旁注,Java 约定规定类名用大写字母声明。myClass 应该是 MyClass,而 myThread 应该是 myThread。不过,这与运行时问题无关。

于 2012-09-05T02:16:38.760 回答
2

您正在重复提交应用程序的主线程RunnableExecutorService我不确定run()在主线程上调用的定义行为(如果有的话,可能是未定义的)是什么,但这肯定是不正确的。您想创建新myThread对象并将它们提交给ExecutorService

于 2012-09-05T02:10:48.060 回答