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

 验证:线程启动的时间开销大于方法调用的时间开销

 

相关文章:

  • 2021-11-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-02
  • 2021-09-04
  • 2021-11-21
猜你喜欢
  • 2021-07-08
  • 2022-12-23
  • 2021-12-19
  • 2022-01-25
  • 2022-12-23
  • 2022-12-23
  • 2021-08-21
相关资源
相似解决方案