cari

Rumah  >  Soal Jawab  >  teks badan

java - 怎么调出并发不确定性的效果

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中文网2807 hari yang lalu605

membalas semua(2)saya akan balas

  • 天蓬老师

    天蓬老师2017-04-17 17:35:42

    Anda boleh menggunakan tidur:

    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();
        }
    }

    balas
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:35:42

      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();
        }
        
        

    Saya menggantikan yield() dalam soalan dengan sleep() Kaedah yield() hanya boleh memberikan thread dengan keutamaan yang sama peluang untuk dilaksanakan. Mungkin benang utama mempunyai keutamaan yang lebih tinggi daripada benang anak

    balas
    0
  • Batalbalas