当前位置: 移动技术网 > IT编程>开发语言>Java > Java多线程编程中synchronized线程同步的教程

Java多线程编程中synchronized线程同步的教程

2019年07月22日  | 移动技术网IT编程  | 我要评论

文山小说网,破釜沉舟的历史人物,尘埃粒子计数器

0.关于线程同步
(1)为什么需要同步多线程?
线程的同步是指让多个运行的线程在一起良好地协作,达到让多线程按要求合理地占用释放资源。我们采用java中的同步代码块和同步方法达到这样的目的。比如这样的解决多线程无固定序执行的问题:

public class twothreadtest {
  public static void main(string[] args) {
    thread th1= new mythread1();
    thread th2= new mythread2();
    th1.start();
    th2.start();
  }
}

class mythread2 extends thread{
  @override
  public void run() {
    for( int i=0;i<10;i++)
      system. out.println( "thread 1 counter:"+i);
  }
}

class mythread1 extends thread{
  @override
  public void run() {
    for( int i=0;i<10;i++)
      system. out.println( "thread 2 counter:"+i);
  }  
}

这种状态下多线程执行的结果是随机地去任意插入执行,这完全取决于jvm对于线程的调度,在很多要求定序执行的情况下,这种随机执行的状态显然是不合要求的。

public class threadtest {
  public static void main(string[] args) {
    mythread thread = new mythread();
    thread th1= new thread(thread);
    thread th2= new thread(thread);
    th1.start();
    th2.start();
  }

}

class mythread implements runnable{
  @override
  public synchronized void run() {
    for( int i=0;i<10;i++)
      system. out.println(thread. currentthread().getname()+" counter:"+i);
  }
}

使用了同步方法后我们就可以控制线程独占执行体对象,这样在执行的过程中就可以使得线程将执行体上的任务一次性执行完后退出锁定状态,jvm再调度另一个线程进来一次性运行执行体内的任务。

(2)线程创建运行的范式:
在以前我们也有自己的线程创建和运行的编程范式,一般是定义一个执行类重写run()方法,但是这种方式将执行体和执行的任务放在了一起,从软件工程的角度来看不利于解耦。一个线程的执行的意思是说线程通过执行对象执行了某个对象的某个任务,从这个角度来说,将任务的规定者从执行类中分离出来可以使得多线程编程的各个角色明晰出来,进而获得良好地解耦,以下就是线程创建和执行的编程范式:

public class formalthreadclass {
  public static void main(string[] args) {
    thread thread = new thread( new myrunnable());
    thread.start();
  }
}

class myrunnable implements runnable{
  mytask mytask = new mytask();
  @override
  public void run() {
    mytask.dotask();
  }
}

class mytask{
  public void dotask() {
    system. out.println( "this is real tasking");
  }
}


1. synchronized原理
在java中,每一个对象有且仅有一个同步锁。这也意味着,同步锁是依赖于对象而存在。
当我们调用某对象的synchronized方法时,就获取了该对象的同步锁。例如,synchronized(obj)就获取了“obj这个对象”的同步锁。
不同线程对同步锁的访问是互斥的。也就是说,某时间点,对象的同步锁只能被一个线程获取到!通过同步锁,我们就能在多线程中,实现对“对象/方法”的互斥访问。 例如,现在有两个线程a和线程b,它们都会访问“对象obj的同步锁”。假设,在某一时刻,线程a获取到“obj的同步锁”并在执行一些操作;而此时,线程b也企图获取“obj的同步锁” —— 线程b会获取失败,它必须等待,直到线程a释放了“该对象的同步锁”之后线程b才能获取到“obj的同步锁”从而才可以运行。

2. synchronized基本规则
我们将synchronized的基本规则总结为下面3条,并通过实例对它们进行说明。
第一条: 当一个线程访问“某对象”的“synchronized方法”或者“synchronized代码块”时,其他线程对“该对象”的该“synchronized方法”或者“synchronized代码块”的访问将被阻塞。
第二条: 当一个线程访问“某对象”的“synchronized方法”或者“synchronized代码块”时,其他线程仍然可以访问“该对象”的非同步代码块。
第三条: 当一个线程访问“某对象”的“synchronized方法”或者“synchronized代码块”时,其他线程对“该对象”的其他的“synchronized方法”或者“synchronized代码块”的访问将被阻塞。
(1)第一条:
当一个线程访问“某对象”的“synchronized方法”或者“synchronized代码块”时,其他线程对“该对象”的该“synchronized方法”或者“synchronized代码块”的访问将被阻塞。 下面是“synchronized代码块”对应的演示程序。

class myrunable implements runnable {

 @override
 public void run() {
  synchronized(this) {
   try { 
    for (int i = 0; i < 5; i++) {
     thread.sleep(100); // 休眠100ms
     system.out.println(thread.currentthread().getname() + " loop " + i); 
    }
   } catch (interruptedexception ie) { 
   }
  } 
 }
}

public class demo1_1 {

 public static void main(string[] args) { 
  runnable demo = new myrunable();  // 新建“runnable对象”

  thread t1 = new thread(demo, "t1"); // 新建“线程t1”, t1是基于demo这个runnable对象
  thread t2 = new thread(demo, "t2"); // 新建“线程t2”, t2是基于demo这个runnable对象
  t1.start();       // 启动“线程t1”
  t2.start();       // 启动“线程t2” 
 } 
}

运行结果:

t1 loop 0
t1 loop 1
t1 loop 2
t1 loop 3
t1 loop 4
t2 loop 0
t2 loop 1
t2 loop 2
t2 loop 3
t2 loop 4

结果说明:run()方法中存在“synchronized(this)代码块”,而且t1和t2都是基于"demo这个runnable对象"创建的线程。这就意味着,我们可以将synchronized(this)中的this看作是“demo这个runnable对象”;因此,线程t1和t2共享“demo对象的同步锁”。所以,当一个线程运行的时候,另外一个线程必须等待“运行线程”释放“demo的同步锁”之后才能运行。
如果你确认,你搞清楚这个问题了。那我们将上面的代码进行修改,然后再运行看看结果怎么样,看看你是否会迷糊。修改后的源码如下:

class mythread extends thread {

 public mythread(string name) {
  super(name);
 }

 @override
 public void run() {
  synchronized(this) {
   try { 
    for (int i = 0; i < 5; i++) {
     thread.sleep(100); // 休眠100ms
     system.out.println(thread.currentthread().getname() + " loop " + i); 
    }
   } catch (interruptedexception ie) { 
   }
  } 
 }
}

public class demo1_2 {

 public static void main(string[] args) { 
  thread t1 = new mythread("t1"); // 新建“线程t1”
  thread t2 = new mythread("t2"); // 新建“线程t2”
  t1.start();       // 启动“线程t1”
  t2.start();       // 启动“线程t2” 
 } 
}

代码说明:比较demo1_2 和 demo1_1,我们发现,demo1_2中的mythread类是直接继承于thread,而且t1和t2都是mythread子线程。
幸运的是,在“demo1_2的run()方法”也调用了synchronized(this),正如“demo1_1的run()方法”也调用了synchronized(this)一样!
那么,demo1_2的执行流程是不是和demo1_1一样呢?运行结果:

t1 loop 0
t2 loop 0
t1 loop 1
t2 loop 1
t1 loop 2
t2 loop 2
t1 loop 3
t2 loop 3
t1 loop 4
t2 loop 4

结果说明:
如果这个结果一点也不令你感到惊讶,那么我相信你对synchronized和this的认识已经比较深刻了。否则的话,请继续阅读这里的分析。
synchronized(this)中的this是指“当前的类对象”,即synchronized(this)所在的类对应的当前对象。它的作用是获取“当前对象的同步锁”。
对于demo1_2中,synchronized(this)中的this代表的是mythread对象,而t1和t2是两个不同的mythread对象,因此t1和t2在执行synchronized(this)时,获取的是不同对象的同步锁。对于demo1_1对而言,synchronized(this)中的this代表的是myrunable对象;t1和t2共同一个myrunable对象,因此,一个线程获取了对象的同步锁,会造成另外一个线程等待。
(2)第二条:
当一个线程访问“某对象”的“synchronized方法”或者“synchronized代码块”时,其他线程仍然可以访问“该对象”的非同步代码块。
下面是“synchronized代码块”对应的演示程序。

class count {

 // 含有synchronized同步块的方法
 public void synmethod() {
  synchronized(this) {
   try { 
    for (int i = 0; i < 5; i++) {
     thread.sleep(100); // 休眠100ms
     system.out.println(thread.currentthread().getname() + " synmethod loop " + i); 
    }
   } catch (interruptedexception ie) { 
   }
  } 
 }

 // 非同步的方法
 public void nonsynmethod() {
  try { 
   for (int i = 0; i < 5; i++) {
    thread.sleep(100);
    system.out.println(thread.currentthread().getname() + " nonsynmethod loop " + i); 
   }
  } catch (interruptedexception ie) { 
  }
 }
}

public class demo2 {

 public static void main(string[] args) { 
  final count count = new count();
  // 新建t1, t1会调用“count对象”的synmethod()方法
  thread t1 = new thread(
    new runnable() {
     @override
     public void run() {
      count.synmethod();
     }
    }, "t1");

  // 新建t2, t2会调用“count对象”的nonsynmethod()方法
  thread t2 = new thread(
    new runnable() {
     @override
     public void run() {
      count.nonsynmethod();
     }
    }, "t2"); 


  t1.start(); // 启动t1
  t2.start(); // 启动t2
 } 
}

运行结果:

t1 synmethod loop 0
t2 nonsynmethod loop 0
t1 synmethod loop 1
t2 nonsynmethod loop 1
t1 synmethod loop 2
t2 nonsynmethod loop 2
t1 synmethod loop 3
t2 nonsynmethod loop 3
t1 synmethod loop 4
t2 nonsynmethod loop 4

结果说明:
主线程中新建了两个子线程t1和t2。t1会调用count对象的synmethod()方法,该方法内含有同步块;而t2则会调用count对象的nonsynmethod()方法,该方法不是同步方法。t1运行时,虽然调用synchronized(this)获取“count的同步锁”;但是并没有造成t2的阻塞,因为t2没有用到“count”同步锁。
(3)第三条:
当一个线程访问“某对象”的“synchronized方法”或者“synchronized代码块”时,其他线程对“该对象”的其他的“synchronized方法”或者“synchronized代码块”的访问将被阻塞。
我们将上面的例子中的nonsynmethod()方法体的也用synchronized(this)修饰。修改后的源码如下:

class count {

 // 含有synchronized同步块的方法
 public void synmethod() {
  synchronized(this) {
   try { 
    for (int i = 0; i < 5; i++) {
     thread.sleep(100); // 休眠100ms
     system.out.println(thread.currentthread().getname() + " synmethod loop " + i); 
    }
   } catch (interruptedexception ie) { 
   }
  } 
 }

 // 也包含synchronized同步块的方法
 public void nonsynmethod() {
  synchronized(this) {
   try { 
    for (int i = 0; i < 5; i++) {
     thread.sleep(100);
     system.out.println(thread.currentthread().getname() + " nonsynmethod loop " + i); 
    }
   } catch (interruptedexception ie) { 
   }
  }
 }
}

public class demo3 {

 public static void main(string[] args) { 
  final count count = new count();
  // 新建t1, t1会调用“count对象”的synmethod()方法
  thread t1 = new thread(
    new runnable() {
     @override
     public void run() {
      count.synmethod();
     }
    }, "t1");

  // 新建t2, t2会调用“count对象”的nonsynmethod()方法
  thread t2 = new thread(
    new runnable() {
     @override
     public void run() {
      count.nonsynmethod();
     }
    }, "t2"); 


  t1.start(); // 启动t1
  t2.start(); // 启动t2
 } 
}

运行结果:

t1 synmethod loop 0
t1 synmethod loop 1
t1 synmethod loop 2
t1 synmethod loop 3
t1 synmethod loop 4
t2 nonsynmethod loop 0
t2 nonsynmethod loop 1
t2 nonsynmethod loop 2
t2 nonsynmethod loop 3
t2 nonsynmethod loop 4

结果说明:
主线程中新建了两个子线程t1和t2。t1和t2运行时都调用synchronized(this),这个this是count对象(count),而t1和t2共用count。因此,在t1运行时,t2会被阻塞,等待t1运行释放“count对象的同步锁”,t2才能运行。

3. synchronized方法 和 synchronized代码块
“synchronized方法”是用synchronized修饰方法,而 “synchronized代码块”则是用synchronized修饰代码块。
synchronized方法示例

public synchronized void foo1() {
  system.out.println("synchronized methoed");
}
synchronized代码块
public void foo2() {
  synchronized (this) {
    system.out.println("synchronized methoed");
  }
}

synchronized代码块中的this是指当前对象。也可以将this替换成其他对象,例如将this替换成obj,则foo2()在执行synchronized(obj)时就获取的是obj的同步锁。
synchronized代码块可以更精确的控制冲突限制访问区域,有时候表现更高效率。下面通过一个示例来演示:

// demo4.java的源码
public class demo4 {

  public synchronized void synmethod() {
    for(int i=0; i<1000000; i++)
      ;
  }

  public void synblock() {
    synchronized( this ) {
      for(int i=0; i<1000000; i++)
        ;
    }
  }

  public static void main(string[] args) {
    demo4 demo = new demo4();

    long start, diff;
    start = system.currenttimemillis();        // 获取当前时间(millis)
    demo.synmethod();                // 调用“synchronized方法”
    diff = system.currenttimemillis() - start;    // 获取“时间差值”
    system.out.println("synmethod() : "+ diff);

    start = system.currenttimemillis();        // 获取当前时间(millis)
    demo.synblock();                // 调用“synchronized方法块”
    diff = system.currenttimemillis() - start;    // 获取“时间差值”
    system.out.println("synblock() : "+ diff);
  }
}

(某一次)执行结果:

synmethod() : 11
synblock() : 3

4. 实例锁 和 全局锁
实例锁 -- 锁在某一个实例对象上。如果该类是单例,那么该锁也具有全局锁的概念。
(1)实例锁对应的就是synchronized关键字。
(2)全局锁 -- 该锁针对的是类,无论实例多少个对象,那么线程都共享该锁。
全局锁对应的就是static synchronized(或者是锁在该类的class或者classloader对象上)。
关于“实例锁”和“全局锁”有一个很形象的例子:

pulbic class something {
  public synchronized void issynca(){}
  public synchronized void issyncb(){}
  public static synchronized void csynca(){}
  public static synchronized void csyncb(){}
}

假设,something有两个实例x和y。分析下面4组表达式获取的锁的情况。
(1) x.issynca()与x.issyncb()
(2) x.issynca()与y.issynca()
(3) x.csynca()与y.csyncb()
(4) x.issynca()与something.csynca()

(1) 不能被同时访问。
因为issynca()和issyncb()都是访问同一个对象(对象x)的同步锁!

// locktest1.java的源码
class something {
  public synchronized void issynca(){
    try { 
      for (int i = 0; i < 5; i++) {
        thread.sleep(100); // 休眠100ms
        system.out.println(thread.currentthread().getname()+" : issynca");
      }
    }catch (interruptedexception ie) { 
    } 
  }
  public synchronized void issyncb(){
    try { 
      for (int i = 0; i < 5; i++) {
        thread.sleep(100); // 休眠100ms
        system.out.println(thread.currentthread().getname()+" : issyncb");
      }
    }catch (interruptedexception ie) { 
    } 
  }
}

public class locktest1 {

  something x = new something();
  something y = new something();

  // 比较(01) x.issynca()与x.issyncb() 
  private void test1() {
    // 新建t11, t11会调用 x.issynca()
    thread t11 = new thread(
        new runnable() {
          @override
          public void run() {
            x.issynca();
          }
        }, "t11");

    // 新建t12, t12会调用 x.issyncb()
    thread t12 = new thread(
        new runnable() {
          @override
          public void run() {
            x.issyncb();
          }
        }, "t12"); 


    t11.start(); // 启动t11
    t12.start(); // 启动t12
  }

  public static void main(string[] args) {
    locktest1 demo = new locktest1();
    demo.test1();
  }
}

运行结果:

t11 : issynca
t11 : issynca
t11 : issynca
t11 : issynca
t11 : issynca
t12 : issyncb
t12 : issyncb
t12 : issyncb
t12 : issyncb
t12 : issyncb

(2) 可以同时被访问

因为访问的不是同一个对象的同步锁,x.issynca()访问的是x的同步锁,而y.issynca()访问的是y的同步锁。

// locktest2.java的源码
class something {
  public synchronized void issynca(){
    try { 
      for (int i = 0; i < 5; i++) {
        thread.sleep(100); // 休眠100ms
        system.out.println(thread.currentthread().getname()+" : issynca");
      }
    }catch (interruptedexception ie) { 
    } 
  }
  public synchronized void issyncb(){
    try { 
      for (int i = 0; i < 5; i++) {
        thread.sleep(100); // 休眠100ms
        system.out.println(thread.currentthread().getname()+" : issyncb");
      }
    }catch (interruptedexception ie) { 
    } 
  }
  public static synchronized void csynca(){
    try { 
      for (int i = 0; i < 5; i++) {
        thread.sleep(100); // 休眠100ms
        system.out.println(thread.currentthread().getname()+" : csynca");
      } 
    }catch (interruptedexception ie) { 
    } 
  }
  public static synchronized void csyncb(){
    try { 
      for (int i = 0; i < 5; i++) {
        thread.sleep(100); // 休眠100ms
        system.out.println(thread.currentthread().getname()+" : csyncb");
      } 
    }catch (interruptedexception ie) { 
    } 
  }
}

public class locktest2 {

  something x = new something();
  something y = new something();

  // 比较(02) x.issynca()与y.issynca()
  private void test2() {
    // 新建t21, t21会调用 x.issynca()
    thread t21 = new thread(
        new runnable() {
          @override
          public void run() {
            x.issynca();
          }
        }, "t21");

    // 新建t22, t22会调用 x.issyncb()
    thread t22 = new thread(
        new runnable() {
          @override
          public void run() {
            y.issynca();
          }
        }, "t22"); 


    t21.start(); // 启动t21
    t22.start(); // 启动t22
  }

  public static void main(string[] args) {
    locktest2 demo = new locktest2();

    demo.test2();
  }
}

运行结果:

t21 : issynca
t22 : issynca
t21 : issynca
t22 : issynca
t21 : issynca
t22 : issynca
t21 : issynca
t22 : issynca
t21 : issynca
t22 : issynca

(3) 不能被同时访问
因为csynca()和csyncb()都是static类型,x.csynca()相当于something.issynca(),y.csyncb()相当于something.issyncb(),因此它们共用一个同步锁,不能被同时反问。

// locktest3.java的源码
class something {
  public synchronized void issynca(){
    try { 
      for (int i = 0; i < 5; i++) {
        thread.sleep(100); // 休眠100ms
        system.out.println(thread.currentthread().getname()+" : issynca");
      }
    }catch (interruptedexception ie) { 
    } 
  }
  public synchronized void issyncb(){
    try { 
      for (int i = 0; i < 5; i++) {
        thread.sleep(100); // 休眠100ms
        system.out.println(thread.currentthread().getname()+" : issyncb");
      }
    }catch (interruptedexception ie) { 
    } 
  }
  public static synchronized void csynca(){
    try { 
      for (int i = 0; i < 5; i++) {
        thread.sleep(100); // 休眠100ms
        system.out.println(thread.currentthread().getname()+" : csynca");
      } 
    }catch (interruptedexception ie) { 
    } 
  }
  public static synchronized void csyncb(){
    try { 
      for (int i = 0; i < 5; i++) {
        thread.sleep(100); // 休眠100ms
        system.out.println(thread.currentthread().getname()+" : csyncb");
      } 
    }catch (interruptedexception ie) { 
    } 
  }
}

public class locktest3 {

  something x = new something();
  something y = new something();

  // 比较(03) x.csynca()与y.csyncb()
  private void test3() {
    // 新建t31, t31会调用 x.issynca()
    thread t31 = new thread(
        new runnable() {
          @override
          public void run() {
            x.csynca();
          }
        }, "t31");

    // 新建t32, t32会调用 x.issyncb()
    thread t32 = new thread(
        new runnable() {
          @override
          public void run() {
            y.csyncb();
          }
        }, "t32"); 


    t31.start(); // 启动t31
    t32.start(); // 启动t32
  }

  public static void main(string[] args) {
    locktest3 demo = new locktest3();

    demo.test3();
  }
}

运行结果:

t31 : csynca
t31 : csynca
t31 : csynca
t31 : csynca
t31 : csynca
t32 : csyncb
t32 : csyncb
t32 : csyncb
t32 : csyncb
t32 : csyncb

(4) 可以被同时访问
因为issynca()是实例方法,x.issynca()使用的是对象x的锁;而csynca()是静态方法,something.csynca()可以理解对使用的是“类的锁”。因此,它们是可以被同时访问的。

// locktest4.java的源码
class something {
  public synchronized void issynca(){
    try { 
      for (int i = 0; i < 5; i++) {
        thread.sleep(100); // 休眠100ms
        system.out.println(thread.currentthread().getname()+" : issynca");
      }
    }catch (interruptedexception ie) { 
    } 
  }
  public synchronized void issyncb(){
    try { 
      for (int i = 0; i < 5; i++) {
        thread.sleep(100); // 休眠100ms
        system.out.println(thread.currentthread().getname()+" : issyncb");
      }
    }catch (interruptedexception ie) { 
    } 
  }
  public static synchronized void csynca(){
    try { 
      for (int i = 0; i < 5; i++) {
        thread.sleep(100); // 休眠100ms
        system.out.println(thread.currentthread().getname()+" : csynca");
      } 
    }catch (interruptedexception ie) { 
    } 
  }
  public static synchronized void csyncb(){
    try { 
      for (int i = 0; i < 5; i++) {
        thread.sleep(100); // 休眠100ms
        system.out.println(thread.currentthread().getname()+" : csyncb");
      } 
    }catch (interruptedexception ie) { 
    } 
  }
}

public class locktest4 {

  something x = new something();
  something y = new something();

  // 比较(04) x.issynca()与something.csynca()
  private void test4() {
    // 新建t41, t41会调用 x.issynca()
    thread t41 = new thread(
        new runnable() {
          @override
          public void run() {
            x.issynca();
          }
        }, "t41");

    // 新建t42, t42会调用 x.issyncb()
    thread t42 = new thread(
        new runnable() {
          @override
          public void run() {
            something.csynca();
          }
        }, "t42"); 


    t41.start(); // 启动t41
    t42.start(); // 启动t42
  }

  public static void main(string[] args) {
    locktest4 demo = new locktest4();

    demo.test4();
  }
}

运行结果:

t41 : issynca
t42 : csynca
t41 : issynca
t42 : csynca
t41 : issynca
t42 : csynca
t41 : issynca
t42 : csynca
t41 : issynca
t42 : csynca

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网