Thread thread2 = new Thread()

时间:2021-08-26 09:47:47

  Thread thread2 = new Thread() {

  @Override

  public void run() {

  test.function();

  }

  };

  thread1.start();

  thread2.start();

  }

  }

  class TestCase {

  public synchronized void function() {// add synchronized keyword.

  for (int i = 0; i < 5; i++) {

  System.out.println(Thread.currentThread()。getName() + " executed result: " + i);

  }

  }

  }

  执行程序。得到的输出结果总是例如以下:

  Thread-0 executed result: 0

  Thread-0 executed result: 1

  Thread-0 executed result: 2

  Thread-0 executed result: 3

  Thread-0 executed result: 4

  Thread-1 executed result: 0

  Thread-1 executed result: 1

  Thread-1 executed result: 2

  Thread-1 executed result: 3

  Thread-1 executed result: 4

  从输出结果能够看出,同步了方法之后,两个线程顺序输出。说明线程Thread-1进入function方法后,线程Thread-2在方法外等待,等Thread-1运行完后释放锁,Thread-2才进入方法运行。

  可是我们对上面的代码稍作改动。看看同步方法。对于不同的对象情况下是否都有线程同步的效果。

  [測试程序2.2]

  /**

  * Test case 2.2. synchronized method but different objects.

  */

  public class Test {

  public static void main(String[] args) {

  // There are two objects.

  final TestCase test1 = new TestCase();

  final TestCase test2 = new TestCase();

  Thread thread1 = new Thread() {

  @Override

  public void run() {

  test1.function();

  }

  };

  Thread thread2 = new Thread() {

  @Override

  public void run() {

  test2.function();

  }

  };

  thread1.start();

  thread2.start();

  }

  }

  class TestCase {

  public synchronized void function() {// add synchronized keyword.

  for (int i = 0; i < 5; i++) {

  System.out.println(Thread.currentThread()。getName() + " executed result: " + i);

  }

  }

  }

  执行程序,某次的执行结果例如以下:

  Thread-0 executed result: 0

  Thread-0 executed result: 1

  Thread-1 executed result: 0

  Thread-1 executed result: 1

  Thread-0 executed result: 2

  Thread-0 executed result: 3

  Thread-0 executed result: 4

  Thread-1 executed result: 2

  Thread-1 executed result: 3

  Thread-1 executed result: 4

  从以上结果能够看出,同步方法时,当一个线程进入一个对象的这个同步方法时。还有一个线程能够进入这个类的别的对象的同一个同步方法。

  同步方法小结

  在多线程中,同步方法时:

  同步方法,属于对象锁,仅仅是对一个对象上锁;

  一个线程进入这个对象的同步方法,其它线程则进不去这个对象全部被同步的方法。能够进入这个对象未被同步的其它方法;

  一个线程进入这个对象的同步方法,其它线程能够进入同一个类的其它对象的全部方法(包含被同步的方法)。

  同步方法仅仅对单个对象实用。

  对静态方法的同步

  上面是对普通的方法进行同步,发现仅仅能锁对象。那么这次我们试着同步静态方法看会有什么结果。与上面的[測试程序2.2]来进行对照。

  [測试程序3.1]

  /**

  * Test case 3.1. synchronized static method.

  */

  public class Test {

  public static void main(String[] args) {

  // There are two objects.

  final TestCase test1 = new TestCase();

  final TestCase test2 = new TestCase();

  Thread thread1 = new Thread() {

  @Override

  public void run() {

  test1.function();

  }

  };

版权声明:本文博客原创文章,博客,未经同意,不得转载。