Thread thread2 = new Thread()

  Thread thread2 = new Thread() {多线程

  @Overrideide

  public void run() {线程

  test.function();对象

  }get

  };同步

  thread1.start();博客

  thread2.start();io

  }function

  }class

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

  }

  };

相关文章
相关标签/搜索