码迷,mamicode.com
首页 > 编程语言 > 详细

21 线程同步

时间:2016-09-04 22:00:41      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

关键字:synchronized

 

class Service

{

  public void fun1()

  {

    synchronized(this)//同步代码块

    {

      try{

        Thread.sleep(3*1000);

      }

      catch(Exception e)

      {

         System.out.println(e);

      }

      System.out.println("fun1");

    }

  }

  

  public void fun2()

  {

    synchronized(this) //同步代码块

    {

      System.out.println("fun2");

    }

  }

 

class MyThread1 implements Runnable

{

  private Service service;

  public MyThread1(Service service)

  {

    this.service=service;

  }

  public void run()

  {

    Serive.fun1();

  }

}

 

 

class MyThread2 implements Runnable

{

  private Service service;

  public MyThread2(Service service)

  {

    this.service=service;

  }

  public void run()

  {

    Serive.fun2();

  }

}

 

class Test

{

  public static void main(String args[])

  {

    Service service=new Service();

    Thread t1=new Thread(new MyThread1(service));

    Thread t2=new Thread(new MyThread2(service));

 

    t1.start();

    t2.start();

  }

}

 

21 线程同步

标签:

原文地址:http://www.cnblogs.com/ansen312/p/5840238.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!