`

线程总结(synchronized关键字)

阅读更多

一.Java的synchronized使用方法总结:

把synchronized当做函数修饰符时,示例代码如下:

 public synchronized void method(){

       //……

}

这也就是同步方法,那这时synchronied锁定的是哪个对象呢?他锁定的是调用这个同步方法对象,也就是说,当一个对象P1在不同的线程中执行这个同步方法时,它们之间也会形成互斥,达到同步的效果。但是这个对象所属的Class所产生的另一个对象P2却能任意调用这个别加了synchronied关键字的方法。

以上代码等同于如下代码:

public void method(){

       synchronized(this){

              //……
        }

}

this 指的是什么?他指的就是调用这个方法的对象.


二.举例:

1.public class synchro implements Runnable {
 static int b = 100;

 static synchro ss = new synchro();

 static synchro ss1 = new synchro();

 public synchronized void m1() throws Exception {

  System.out.println("m111");
  b--;
  Thread.sleep(5000);
  System.out.println("Thread=" + Thread.currentThread().getName() + " "
    + this + " " + "b=:" + b);

 }

 public void m2() throws Exception {

  System.out.println("m2");
  b--;
  System.out.println("Thread=" + Thread.currentThread().getName() + " "
    + this + " " + b);

 }

 public void run() {
  try {
   m1();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static void main(String args[]) throws Exception {

  Thread tt = new Thread(ss);
  Thread tt1 = new Thread(ss);
  tt.start();
  tt1.start();
  ss.m2();
  ss.m1();

 }
}
// 相同对象中各线程之间同步(synchronized)方法与非同步方法之间不互斥。
// 一种执行结果:
m111
m2
Thread=main synchro@4a5ab2 98
Thread=Thread-0 synchro@4a5ab2 b=:98
m111
Thread=main synchro@4a5ab2 b=:97
m111
Thread=Thread-1 synchro@4a5ab2 b=:96

 

2.

public class CopyOfsynchro implements Runnable {
 static int b = 100;

 public synchronized void m1() throws Exception {

  System.out.println("m1");
  b--;
  Thread.sleep(5000);
  System.out.println("m1" + "Thread=" + Thread.currentThread().getName()
    + " " + this + " " + "b=:" + b);

 }

 public synchronized void m2() throws Exception {

  System.out.println("m2");
  b--;
  Thread.sleep(1000);
  System.out.println("m2" + "Thread=" + Thread.currentThread().getName()
    + " " + this + " " + b);

 }

 public void run() {
  try {
   m1();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static void main(String args[]) throws Exception {
  CopyOfsynchro ss = new CopyOfsynchro();
  CopyOfsynchro ss1 = new CopyOfsynchro();
  Thread tt = new Thread(ss);// ss,tt与tt1是同一对象的不同线程(ss.m2()显示的是主线程)
  Thread tt1 = new Thread(ss);
  Thread tt2 = new Thread(ss1);// tt2与tt,tt1是不同对象的不同线程
  tt.start();
  tt2.start();
  ss.m2();
  tt1.start();

 }
}
// 相同对象中各线程之间互斥,不同对象中各线程之间不互斥

// 一种执行结果:
m1
m1
m1Thread=Thread-0 CopyOfsynchro@6e1408 b=:98
m2
m1Thread=Thread-2 CopyOfsynchro@e53108 b=:98
m2Thread=main CopyOfsynchro@6e1408 97
m1
m1Thread=Thread-1 CopyOfsynchro@6e1408 b=:96

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics