---
title: "多线程同步与互斥"
author: "willpower"
date: "2007-03-07T11:44:29Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2007-03-07T11:44:29Z"
id: 57955
url: "https://willpower.iteye.com/blog/57955"
---

和作者联系：[djb\_skyface@tom.com](mailto:djb_skyface@tom.com)

* * *

 

    接触多线程已经不少时间了,也做了不少事情,但是一直觉得用起来不那么顺手,在debug的时候,往往会比较担心在同步上出什么问题,想起"程序员最怕的是自己写的代码"这句话,觉得真是不假.  
    终于有一天,我觉得是时候把这个问题弄清楚了,所以,我就在网上找相关的内容看,结果竟然是找不到在我这个阶段应该看的,不是太简单,就是一笔带过,不知所云.  
    废了九牛二虎之力,终于差不多弄清楚了,其中有不少误区,以前认为的和真理相差甚大.想起自己花费的时间,真是觉得有点多,所以把它写出来,一是防止自己以后又会忘掉,二是给像我一样的似懂非懂者留下一点可以参考的东东.  
    闲话少说,转入正题!

 

* * *

 

    先从线程的创建说起.线程的创建一共有两种形式:

 

* * *

    一种是继承自Thread类.Thread 类是一个具体的类，即不是抽象类，该类封装了线程的行为。要创建一个线程，程序员必须创建一个从 Thread 类导出的新类。程序员通过覆盖 Thread 的 run() 函数来完成有用的工作。用户并不直接调用此函数；而是通过调用 Thread 的 start() 函数，该函数再调用 run()。  
     
    例如:

 

java 代码

01. public class Test extends Thread{
02. public Test(){
03. }
04. public static void main(String args\[]){
05. Test t1 = new Test();
06. Test t2 = new Test();
07. t1.start();
08. t2.start();
09. }
10. public void run(){
11. //do thread's things
12. }
13. }

 

* * *

      
    另一种是实现Runnable接口,此接口只有一个函数，run()，此函数必须由实现了此接口的类实现。  
     
    例如:

 

java 代码

01. public class Test implements Runnable{
02. Thread thread1;
03. Thread thread2;
04. public Test(){
05. thread1 = new Thread(this,"1");
06. thread2 = new Thread(this,"2");
07. }
08. public static void main(String args\[]){
09. Test t = new Test();
10. t.startThreads();
11. }
12. public void run(){
13. //do thread's things
14. }
15. public void startThreads(){
16. thread1.start();
17. thread2.start();
18. }
19. }

    两种创建方式看起来差别不大,但是弄不清楚的话，也许会将你的程序弄得一团糟。两者区别有以下几点：

1.当你想继承某一其它类时,你只能用后一种方式.

2.第一种因为继承自Thread,只创建了自身对象,但是在数量上，需要几个线程，就得创建几个自身对象；第二种只创建一个自身对象，却创建几个Thread对象.而两种方法重大的区别就在于此，请你考虑：如果你在第一种里创建数个自身对象并且start()后，你会发现好像synchronized不起作用了，已经加锁的代码块或者方法居然同时可以有几个线程进去，而且同样一个变量，居然可以有好几个线程同时可以去更改它。（例如下面的代码）这是因为，在这个程序中，虽然你起了数个线程，可是你也创建了数个对象，而且，每个线程对应了每个对象也就是说，每个线程更改和占有的对象都不一样，所以就出现了同时有几个线程进入一个方法的现象，其实，那也不是一个方法，而是不同对象的相同的方法。所以，这时候你要加锁的话，只能将方法或者变量声明为静态，将static加上后，你就会发现，线程又能管住方法了，同时不可能有两个线程进入同样一个方法，那是因为，现在不是每个对象都拥有一个方法了，而是所有的对象共同拥有一个方法，这个方法就是静态方法。

    而你如果用第二种方法使用线程的话，就不会有上述的情况，因为此时，你只创建了一个自身对象，所以，自身对象的属性和方法对于线程来说是共有的。

    因此，我建议，最好用后一种方法来使用线程。

java 代码

01. public class mainThread extends Thread{
02. int i=0;
03. public static void main(String args\[]){
04. mainThread m1 = new mainThread();
05. mainThread m2 = new mainThread();
06. mainThread m3 = new mainThread();
07. mainThread m4 = new mainThread();
08. mainThread m5 = new mainThread();
09. mainThread m6 = new mainThread();
10. m1.start();
11. m2.start();
12. m3.start();
13. m4.start();
14. m5.start();
15. m6.start();
16. }
17. public synchronized void t1(){
18. i=++i;
19. try{
20. Thread.sleep(500);
21. }
22. catch(Exception e){}
23. //每个线程都进入各自的t1()方法，分别打印各自的i
24. System.out.println(Thread.currentThread().getName()+" "+i);
25. }
26. public void run(){
27. synchronized(this){
28. while (true) {
29. t1();
30. }
31. }
32. }
33. }

 

 

* * *

 

 

    下面我们来讲synchronized的4种用法吧:

    1.方法声明时使用,放在范围操作符(public等)之后,返回类型声明(void等)之前.即一次只能有一个线程进入该方法,其他线程要想在此时调用该方法,只能排队等候,当前线程(就是在synchronized方法内部的线程)执行完该方法后,别的线程才能进入.  
   
      例如:

      public synchronized void synMethod() {  
        //方法体  
      }

    2.对某一代码块使用,synchronized后跟括号,括号里是变量,这样,一次只有一个线程进入该代码块.例如:

     

java 代码

1. public int synMethod(int a1){
2. synchronized(a1) {
3. //一次只能有一个线程进入
4. }
5. }

    3.synchronized后面括号里是一对象,此时,线程获得的是对象锁.例如:

> > > java 代码
> > > 
> > > 01. public class MyThread implements Runnable {
> > > 02. public static void main(String args\[]) {
> > > 03. MyThread mt = new MyThread();
> > > 04. Thread t1 = new Thread(mt, "t1");
> > > 05. Thread t2 = new Thread(mt, "t2");
> > > 06. Thread t3 = new Thread(mt, "t3");
> > > 07. Thread t4 = new Thread(mt, "t4");
> > > 08. Thread t5 = new Thread(mt, "t5");
> > > 09. Thread t6 = new Thread(mt, "t6");
> > > 10. t1.start();
> > > 11. t2.start();
> > > 12. t3.start();
> > > 13. t4.start();
> > > 14. t5.start();
> > > 15. t6.start();
> > > 16. }
> > > 17. public void run() {
> > > 18. synchronized (this) {
> > > 19. System.out.println(Thread.currentThread().getName());
> > > 20. }
> > > 21. }
> > > 22. }
> > > 
> > >    
> > >     对于3,如果线程进入,则得到对象锁,那么别的线程在该类所有对象上的任何操作都不能进行.在对象级使用锁通常是一种比较粗糙的方法。为什么要将整个对象都上锁，而不允许其他线程短暂地使用对象中其他同步方法来访问共享资源？如果一个对象拥有多个资源，就不需要只为了让一个线程使用其中一部分资源，就将所有线程都锁在外面。由于每个对象都有锁，可以如下所示使用虚拟对象来上锁：

> > > java 代码
> > > 
> > > 01. class FineGrainLock {
> > > 02. MyMemberClass x, y;
> > > 03. Object xlock = new Object(), ylock = new Object();
> > > 04. public void foo() {
> > > 05. synchronized(xlock) {
> > > 06. //access x here
> > > 07. }
> > > 08. //do something here - but don't use shared resources
> > > 09. synchronized(ylock) {
> > > 10. //access y here
> > > 11. }
> > > 12. }
> > > 13. public void bar() {
> > > 14. synchronized(this) {
> > > 15. //access both x and y here
> > > 16. }
> > > 17. //do something here - but don't use shared resources
> > > 18. }
> > > 19. }

    4.synchronized后面括号里是类.例如:

> > > java 代码
> > > 
> > > 01. class ArrayWithLockOrder{
> > > 02. private static long num\_locks = 0;
> > > 03. private long lock\_order;
> > > 04. private int\[] arr;
> > > 05. public ArrayWithLockOrder(int\[] a)
> > > 06. {
> > > 07. arr = a;
> > > 08. synchronized(ArrayWithLockOrder.class) {//-----------------------------------------这里
> > > 09. num\_locks++;             // 锁数加 1。
> > > 10. lock\_order = num\_locks;  // 为此对象实例设置唯一的 lock\_order。
> > > 11. }
> > > 12. }
> > > 13. public long lockOrder()
> > > 14. {
> > > 15. return lock\_order;
> > > 16. }
> > > 17. public int\[] array()
> > > 18. {
> > > 19. return arr;
> > > 20. }
> > > 21. }
> > > 22. class SomeClass implements Runnable
> > > 23. {
> > > 24. public int sumArrays(ArrayWithLockOrder a1,
> > > 25. ArrayWithLockOrder a2)
> > > 26. {
> > > 27. int value = 0;
> > > 28. ArrayWithLockOrder first = a1;       // 保留数组引用的一个
> > > 29. ArrayWithLockOrder last = a2;        // 本地副本。
> > > 30. int size = a1.array().length;
> > > 31. if (size == a2.array().length)
> > > 32. {
> > > 33. if (a1.lockOrder() &gt; a2.lockOrder())  // 确定并设置对象的锁定
> > > 34. {                                     // 顺序。
> > > 35. first = a2;
> > > 36. last = a1;
> > > 37. }
> > > 38. synchronized(first) {              // 按正确的顺序锁定对象。
> > > 39. synchronized(last) {
> > > 40. int\[] arr1 = a1.array();
> > > 41. int\[] arr2 = a2.array();
> > > 42. for (int i=0; i&lt;size; i++)
> > > 43. value += arr1\[i] + arr2\[i];
> > > 44. }
> > > 45. }
> > > 46. }
> > > 47. return value;
> > > 48. }
> > > 49. public void run() {
> > > 50. //...
> > > 51. }
> > > 52. }

    对于4,如果线程进入,则线程在该类中所有操作不能进行,包括静态变量和静态方法,实际上,对于含有静态方法和静态变量的代码块的同步,我们通常用4来加锁.

以上4种之间的关系：

    锁是和对象相关联的，每个对象有一把锁，为了执行synchronized语句，线程必须能够获得synchronized语句中表达式指定的对象的锁，一个对象只有一把锁，被一个线程获得之后它就不再拥有这把锁，线程在执行完synchronized语句后，将获得锁交还给对象。  
    **在方法前面加上synchronized修饰符即可以将一个方法声明为同步化方法。同步化方法在执行之前获得一个锁。如果这是一个类方法，那么获得的锁是和声明方法的类相关的Class类对象的锁。如果这是一个实例方法，那么此锁是this对象的锁。**

 

* * *

 

  下面谈一谈一些常用的方法:

  wait(),wait(long),notify(),notifyAll()等方法是当前类的实例方法,  
     
        wait()是使持有对象锁的线程释放锁;  
        wait(long)是使持有对象锁的线程释放锁时间为long(毫秒)后,再次获得锁,wait()和wait(0)等价;  
        notify()是唤醒一个正在等待该对象锁的线程,如果等待的线程不止一个,那么被唤醒的线程由jvm确定;  
        notifyAll是唤醒所有正在等待该对象锁的线程.  
        在这里我也重申一下,我们应该优先使用notifyAll()方法,因为唤醒所有线程比唤醒一个线程更容易让jvm找到最适合被唤醒的线程.

    对于上述方法,只有在当前线程中才能使用,否则报运行时错误java.lang.IllegalMonitorStateException: current thread not owner.

 

* * *

 

    下面,我谈一下synchronized和wait()、notify()等的关系:

1.有synchronized的地方不一定有wait,notify

2.有wait,notify的地方必有synchronized.这是因为wait和notify不是属于线程类，而是每一个对象都具有的方法，而且，这两个方法都和对象锁有关，有锁的地方，必有synchronized。

另外，请注意一点：如果要把notify和wait方法放在一起用的话，必须先调用notify后调用wait，因为如果调用完wait，该线程就已经不是current thread了。如下例：

java 代码

01. /\**
02. * Title:        Jdeveloper's Java Projdect
03. * Description:  n/a
04. * Copyright:    Copyright (c) 2001
05. * Company:      soho  http://www.ChinaJavaWorld.com
06. * @author jdeveloper@21cn.com
07. * @version 1.0
08. \*/
09. import java.lang.Runnable;
10. import java.lang.Thread;
11. public class DemoThread
12. implements Runnable {
13. public DemoThread() {
14. TestThread testthread1 = new TestThread(this, "1");
15. TestThread testthread2 = new TestThread(this, "2");
16. testthread2.start();
17. testthread1.start();
18. }
19. public static void main(String\[] args) {
20. DemoThread demoThread1 = new DemoThread();
21. }
22. public void run() {
23. TestThread t = (TestThread) Thread.currentThread();
24. try {
25. if (!t.getName().equalsIgnoreCase("1")) {
26. synchronized (this) {
27. wait();
28. }
29. }
30. while (true) {
31. System.out.println("@time in thread" + t.getName() + "=" +
32. t.increaseTime());
33. if (t.getTime() % 10 == 0) {
34. synchronized (this) {
35. System.out.println("\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*");
36. notify();
37. if (t.getTime() == 100)
38. break;
39. wait();
40. }
41. }
42. }
43. }
44. catch (Exception e) {
45. e.printStackTrace();
46. }
47. }
48. }
49. class TestThread
50. extends Thread {
51. private int time = 0;
52. public TestThread(Runnable r, String name) {
53. super(r, name);
54. }
55. public int getTime() {
56. return time;
57. }
58. public int increaseTime() {
59. return++time;
60. }
61. }

    下面我们用生产者/消费者这个例子来说明他们之间的关系:

> > > java 代码
> > > 
> > > 01. public class test {
> > > 02. public static void main(String args\[]) {
> > > 03. Semaphore s = new Semaphore(1);
> > > 04. Thread t1 = new Thread(s, "producer1");
> > > 05. Thread t2 = new Thread(s, "producer2");
> > > 06. Thread t3 = new Thread(s, "producer3");
> > > 07. Thread t4 = new Thread(s, "consumer1");
> > > 08. Thread t5 = new Thread(s, "consumer2");
> > > 09. Thread t6 = new Thread(s, "consumer3");
> > > 10. t1.start();
> > > 11. t2.start();
> > > 12. t3.start();
> > > 13. t4.start();
> > > 14. t5.start();
> > > 15. t6.start();
> > > 16. }
> > > 17. }
> > > 18. class Semaphore
> > > 19. implements Runnable {
> > > 20. private int count;
> > > 21. public Semaphore(int n) {
> > > 22. this.count = n;
> > > 23. }
> > > 24. public synchronized void acquire() {
> > > 25. while (count == 0) {
> > > 26. try {
> > > 27. wait();
> > > 28. }
> > > 29. catch (InterruptedException e) {
> > > 30. //keep trying
> > > 31. }
> > > 32. }
> > > 33. count--;
> > > 34. }
> > > 35. public synchronized void release() {
> > > 36. while (count == 10) {
> > > 37. try {
> > > 38. wait();
> > > 39. }
> > > 40. catch (InterruptedException e) {
> > > 41. //keep trying
> > > 42. }
> > > 43. }
> > > 44. count++;
> > > 45. notifyAll(); //alert a thread that's blocking on this semaphore
> > > 46. }
> > > 47. public void run() {
> > > 48. while (true) {
> > > 49. if (Thread.currentThread().getName().substring(0,8).equalsIgnoreCase("consumer")) {
> > > 50. acquire();
> > > 51. }
> > > 52. else if (Thread.currentThread().getName().substring(0,8).equalsIgnoreCase("producer")) {
> > > 53. release();
> > > 54. }
> > > 55. System.out.println(Thread.currentThread().getName() + " " + count);
> > > 56. }
> > > 57. }
> > > 58. }
> > > 
> > >        生产者生产,消费者消费,一般没有冲突,但当库存为0时,消费者要消费是不行的,但当库存为上限(这里是10)时,生产者也不能生产.请好好研读上面的程序,你一定会比以前进步很多.

      上面的代码说明了synchronized和wait,notify没有绝对的关系,在synchronized声明的方法、代码块中,你完全可以不用wait,notify等方法,但是,如果当线程对某一资源存在某种争用的情况下,你必须适时得将线程放入等待或者唤醒.

 

* * *

 

文章终于写完了,基本上将我学习所得全部写出来了,不过也留下些许遗憾,比如synchronized后是类时的深入的说明及讨论.而且,文章由于自己能力有限,有些地方肯定会有错误,希望看过有何建议和批评,请发帖在下面,我会修正该文.谢谢!