Java中的线程行为

时间:2012-09-05 02:02:00

标签: java

我正在运行下面的程序但由于某种原因,它看起来不像我正在使用run()方法。基本上我试图发现线程的行为。我得到的结果如下:

pqni392fr8dchsdmajglvuqsof
pqni392fr8dchsdmajglvuqsof已经醒来了 l79uho1tjtot7pcmk4vhh5t8qc
l79uho1tjtot7pcmk4vhh5t8qc已经醒来了 adfapus6g1fst56daimrudkgji
adfapus6g1fst56daimrudkgji已经醒来了 iqfo9knc99kcb622g36c77m62
iqfo9knc99kcb622g36c77m62已经醒来了 67vdpghqit1a4iv3593451ps0a
67vdpghqit1a4iv3593451ps0a已经醒来了

如你所见,我没有进入线程应该睡眠的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();
    }
}

2 个答案:

答案 0 :(得分: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。但这与运行时问题无关。

答案 1 :(得分:2)

您正在以Runnable的方式将申请的主要帖子重复提交给ExecutorService。我不确定在主线程上调用run()的定义行为(如果有的话,可能是未定义的)是,但它肯定是不正确的。您想要创建新的myThread个对象,并将其提交给ExecutorService