java - 关于线程的强制运行的一个问题?
PHP中文网
PHP中文网 2017-04-17 17:57:58
0
1
364

class MyThread implements Runnable{
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
        
        for(int i=0;i<10;i++){
            System.out.println(Thread.currentThread().getName());
        }
        
    }
    
}





public class Test {
    
    
    public static void main(String[] args) {
        MyThread my = new MyThread();
        Thread t = new Thread(my,"thread-a");
        t.start();
        
        for(int i=0;i<100;i++){
            System.out.println(i);
            if(i>50){
                try {
                    t.join();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            }
        }
        
    }

        

}

代码如上, 我知道在i>50 会强制t运行, 但是t.start()时 线程t 不就已经启动了吗?为什么在i<50时不会输出thread-a?

PHP中文网
PHP中文网

认证0级讲师

reply all(1)
黄舟

What you see is only the result of your single run (due to thread scheduling, thread-a may not start to be output until i > 50). You can see the results you want by running it a few more times:

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template