java - 怎么调出并发不确定性的效果
PHP中文网
PHP中文网 2017-04-17 17:33:42
0
2
601
class HelloWorld {
    public static void main(String[] args) throws InterruptedException {
        Thread myThread = new Thread() {
            public void run(){
                System.out.println("Hello from new Thread!");
            }
        };
        
        myThread.start();
        Thread.yield();
        
        System.out.println("Hello from main Thread!");
        myThread.join();
    }
}

《七周七并发模型》
作者说结果可能是

结果可能一

Hello from main Thread!
Hello from new Thread!

结果可能二

Hello from new Thread!
Hello from main Thread!

为什么我的结果只有一。

PHP中文网
PHP中文网

认证高级PHP讲师

全部回覆(2)
Peter_Zhu

可以用sleep:

class HelloWorld {
    public static void main(String[] args) throws InterruptedException {
        Thread myThread = new Thread() {
            public void run(){
                System.out.println("Hello from new Thread!");
            }
        };
        
        myThread.start();
        Thread.yield();
        Thread.sleep(100);
        System.out.println("Hello from main Thread!");
        myThread.join();
    }
}
伊谢尔伦
  public static void main(String[] args) throws InterruptedException {
        Thread myThread = new Thread(){
            public void run(){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Hello from new Thread!");
            }
        };
        
        myThread.start();
        Thread.sleep(500);
        
        System.out.println("Hello from main Thread!");
        myThread.join();
    }
    
    

我把題主的yield()換成了sleep(),yield()方法只能讓同優先權的執行緒有執行的機會。可能是主執行緒比子執行緒優先權高

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板