1. 程式人生 > >主執行緒中呼叫執行緒的start()

主執行緒中呼叫執行緒的start()

public class Quest implements Runnable
{
    int b = 100;

    public synchronized void m1() throws Exception
    {
        System.out.println("enter m1");
        b = 1000;
        Thread.sleep(3000);
        System.out.println("b="+b);
    }
    
    public void m2() throws Exception
    {
        System.out.println(
"enter m2"); Thread.sleep(3000); b = 2000; } @Override public void run() { try { m1(); } catch (Exception e) { e.printStackTrace(); } } public static
void main(String[] args) { try { Quest quest = new Quest(); // 執行緒從呼叫start()到run()執行需要一定的時間 new Thread(quest).start(); // 所以此處會先執行m2() quest.m2(); System.out.println(quest.b); } catch (Exception e) { e.printStackTrace(); } } }

結果:

  每次先列印 m2