---
title: "Java线程"
author: "0428loveyu"
date: "2014-06-06T16:21:00Z"
tags: []
slug: "java"
draft: false
lastmod: "2014-09-11T23:58:20Z"
id: 2115565
url: "https://fernly.iteye.com/blog/2115565"
---

# 1. 并发：进程与线程

关于并发，一个最直观的例子就是你可以同时听歌还能上网，能用Word。即使在同一个程序中，也可能要同时完成多个任务，比如音乐播放器，你一边听着一首歌，另一边还同时下载其他歌曲，你还想改变一下外观，这些任务之所以能完成，就是基于并发的概念。Java语言从语言级别到API都提供了对并发的支持。

即使计算机只有一个单核的处理器，也经常存在多个进程和线程。操作系统的时间片机制为多进程和多线程提供支持，此时在具体的某一个，只有一个线程能执行任务，但是由于时间片切换非常快，给人感觉好像同时运行的样子。现在多处理器和多核单处理器越来越普遍，可以实现真正意义上的并发。但是要记住，即使是单个处理器，多个核也能实现并发。

## 1.1 进程

进程有自己独立的运行环境，包括完整的系统资源，尤其是用于自己独立的内存空间。进程经常和应用程序（application、program）等同，但实际上一个应用程序背后可能有多个进程存在，进程之间通过Inter Process Communication（IPC）机制进行通信，比如管道（pipes）和套接字（sockets）。IPC不仅用于同一台机器上的进程通信，也支持不同机器上的进程之间的通信。Java虚拟机的实现一般都是单个进程，Java程序可以使用ProcessBuilder对象创建多个进程。多进程Java程序不在这里讨论。

## 1.2 线程

线程存在于进程中，每个进程至少有一个线程。同一个进程内的线程共享进程资源，比如内存空间、打开的文件等。线程也被称为轻量级进程，“轻量级”是指创建一个线程所需要的系统资源开销比进程小，另外，线程之间的切换开销也比进程间小。这使得程序更加高效，但是由于共享进程资源，也可以导致问题，比如不同步。每个线程都定义了单独的执行路径，是能够调度的最小代码单元。

# 2. 创建线程

在Java中创建线程一般有两种方式。1）实现Runnable接口，把要在线程中执行的代码放在run方法当中，然后将Runnable作为Thread的构造参数传递给Thread构造器。2）拓展Thread类，重写run方法执行想要的程序片段。

## 2.1 实现Runnable接口

Runnable接口定义了唯一的run方法，通过在自己的类中实现这一接口，然后将Runnable实例传递给线程类Thread构造函数。下面的代码中实现了一个FirstRunnable的类，实现了Runnable接口的run方法。简单输出一条语句。

```
<span style="font-family:SimHei;font-size:14px;">public class FirstRunnable implements Runnable {

	/*
	 * The code to be executed in thread
	 */
	@Override
	public void run() {
		System.out.println("I am born from: "
				+ Thread.currentThread().getName());
		// 线程的静态方法都是针对当前线程的操作

	}

}</span>
```

实现完Runnable接口之后，在主线程中创建一个新的线程：

```
<span style="font-family:SimHei;font-size:14px;">public class Schedule {

	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		// create  a new thread from main thread
		Thread thread = new Thread(new FirstRunnable());
		thread.start();
		//thread.join();
		
		System.out.println("I am from: " + Thread.currentThread().getName());

	}

}

</span>
```

创建线程后，调用线程的start方法启动线程。这样，我们就实现了一个最简单的多线程程序。

## 2.2 继承Thread

除了实现Runnable接口以外，还可以直接继承Thread类，重写run方法。

```
<span style="font-family:SimHei;font-size:14px;">/**
 * @author Brandon B. Lin
 *
 */
public class SubclassThread extends Thread {

	@Override
	public void run() {
		System.out.println("I am born from: " + Thread.currentThread().getName());
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SubclassThread thread = new SubclassThread();
		thread.start();
		
		System.out.println("I am born from: " + Thread.currentThread().getName());		

	}

}
</span>
```

注意我们启动线程调用的是start方法，而不是run方法，如果我们直接调用run方法也没有问题，但是你会发现run方法中的代码不是在新的线程中执行的，而是在主线程中执行的，也就没有多线程的概念了。

## 2.3 选择哪一种方式

我们来看看Thread类的构造器和run方法是如何工作的，为什么可以选择这两种方式。第一种方法中，向Thread构造器传递了要执行的目标代码，这个构造器代码如下：

```
<span style="font-family:SimHei;font-size:14px;">    public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }</span>
```

我们发现它调用了某个内部方法，再来看看直接继承的情况下创建Thread对象的构造函数，

```
<span style="font-family:SimHei;font-size:14px;">    public Thread() {
        init(null, null, "Thread-" + nextThreadNum(), 0);
    }</span>
```

发现它们原来都调用同一个方法，知识参数不一样而已。那么它们要执行的代码又是怎么回事？对于第一种方式，传递Runnable对象，看一下Thread类的run方法：

```
<span style="font-family:SimHei;font-size:14px;">    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }</span>
```

由于Thread类实现了Runnable接口，所以必须实现run方法，在这个方法内部，如果我们传递了目标代码Runnable，它简单地调用目标的run方法。如果我们直接创建一个Thread对象，什么都不传递，此时这个线程什么也不执行。

当我们继承Thread类重写run方法的时候，线程运行的就是run方法的代码，因此，这两种方式本质上都是一回事。那么到底实践中应该选择哪种方式？JDK给出的建议是，只有当类正在以某种方式增强或者修改时，才应该对类进行拓展。因此，如果不重写Thread类中run之外的方法，最好的方式是实现Runnable接口。这样可以把线程执行的代码和对线程的控制分离开来，是一种很好的编程风格。具体地，Thread类中还定义了其他一些管理线程的方法，比如start方法用于启动线程，getName获取线程名字，getID获取线程ID等。这些方法都是对线程的管理和控制，而线程具体执行的内容，在Runnable的run方法定义，这种分离，把任务实体和执行任务的实体分开，使得代码更加清晰，更加容易复用和维护。（这应该是一种设计模式，应该好好研究！）

另外，如果通过继承Thread类，也就意味着不能再继承其他的类。而实现Runnable接口，仍然允许我们继承其他类，这也是一个优点。

# 3. Thread类的几个方法

Thread类提供了多种形式的构造函数，除此以外还定义了一些用于管理的使用方法。这些方法大致上可以分为两类：静态和非静态。静态方法提供当前线程的一些信息或者影像当前线程的状态。所谓的当前线程，就是调用该方法的线程。比如我们在run方法中调用静态方法：

```
<span style="font-family:SimHei;font-size:14px;">	@Override
	public void run() {
		System.out.println("I am born from: "
				+ Thread.currentThread().getName());
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 线程的静态方法都是针对当前线程的操作

	}</span>
```

调用Thread.sleep使得当前线程休眠一秒，也就是调用run方法的线程休眠一秒钟。当前就是指执行当前代码（比如Thread.sleep(1000)）的线程，理解这一点很重要。

对于Thread中的非静态方法，它们是由其他线程调用，用于管理线程对象。比如在main方法中：

```
<span style="font-family:SimHei;font-size:14px;">	public static void main(String[] args) throws InterruptedException {
		// create  a new thread from main thread
		Thread thread = new Thread(new FirstRunnable());
		thread.start();
		//thread.join();
		
		System.out.println("I am from: " + Thread.currentThread().getName());

	}</span>
```

对于创建的新线程thread，我们在主线程中调用它的start方法，用于启动该线程。

理解这两类方法的区别很重要，程序中的所有代码，都有一个特定的线程来执行它，单线程程序中就是由主线程执行。

## 3.1 Thread构造函数

Thread提供了多种构造函数。可以指定线程执行的Runnable目标、线程名称、线程所属线程组等。这里先列出没有指定线程组的几个构造函数，

```
<span style="font-family:SimHei;font-size:14px;">    public Thread()
    public Thread(Runnable target)
    public Thread(String name) </span>
```

```
<span style="font-family:SimHei;font-size:14px;">    public Thread(Runnable target, String name)</span>
```

其中target为线程要执行的目标代码，name为线程名称。

## 3.2 Thread方法

### 3.2.1 sleep：暂停当前线程

Thrad.sleep方法用于暂停当前线程的执行一段时间，给其他线程或者同一台电脑上的其他程序（进程）让出运行时间。这个方法有两种不同的重载形式：

```
<span style="font-family:SimHei;font-size:14px;">    public static native void sleep(long millis)        throws InterruptedException;
    public static void sleep(long millis, int nanos)    throws InterruptedException</span></span></span>
```

注意到第一个方法是本地（native），而其实第二种形式也是通过调用第一种形式来完成的。方法两种方式都是将当前线程暂停一段时间，具体时间由参数决定，第二种方法更精确一点。但是要注意的是，跟I/O中读入数据的方法类似，这里的时间也只是我们期望的，具体暂停多长时间，受到许多因素影响。比如操作系统提供的时钟精度无法达到参数中的级别，那么暂时的时间将出现误差。另外，处于睡眠状态的线程可能会被中断，此时抛出InterruptedException异常。

下面的例子每次循环中暂停主线程（当前线程）4秒：

```
<span style="font-family:SimHei;font-size:14px;"> public class SleepMessages {
    public static void main(String args[])
        throws InterruptedException {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };

        for (int i = 0;
             i < importantInfo.length;
             i++) {
            //Pause for 4 seconds
           Thread.sleep(4000);
            //Print a message
            System.out.println(importantInfo[i]);
        }
    }
}</span>
```

### 3.2.2 中断

中断是一种信号，用于提醒被中断的线程停下手头正在做的事情，转而做些其他事情。如何处理中断取决于我们的代码，但是结束线程是很常见的一种方式，或者用其他方式处理中断。下面是一个中断的例子，一个线程休眠10秒，主线程调用它的interrupt方法中断：

```
<span style="font-family:SimHei;font-size:14px;">public class FirstRunnable implements Runnable {
	
	/*
	 * The code to be executed in a separately thread
	 */
	@Override
	public void run() {
		System.out.println("I am born from: "
				+ Thread.currentThread().getName());
		try {
			Thread.sleep(10_000);
		} catch (InterruptedException e) {
			System.out.println("Oh My God. I am interrupted!");
		}
		// 线程的静态方法都是针对当前线程的操作

	}

}

        public static void main(String[] args) throws InterruptedException {
		// create  a new thread from main thread
		Thread thread = new Thread(new FirstRunnable());
		thread.start();
		thread.interrupt();
		

	}</span>
```

出现中断异常是被中断的一个标志，但是没有抛出中断异常的线程也可以被中断，尤其是执行很费时的操作时，应该是不是地检查线程是否被中断，通过调用静态方法Thread.interrupted()检测当前线程是否被中断。看例子：

```
<span style="font-family:SimHei;font-size:14px;">/**
 * @author Brandon B. Lin
 *
 */
public class HeavyRunnable implements Runnable {

	
	@Override
	public void run() {
		for (int i=0; i<20; i++) {
			heavyWorh("" + i);
			if (Thread.interrupted()) {
				System.out.println("I am interrupted!");</span>
```

```
<span style="font-family:SimHei;font-size:14px;">			        return;
			}
		}

	}
	
	// do something taking long time
	private void heavyWorh(String input) {
		for(int i = 0; i 500_000_000; i ++) {
			new String(input);
		}
	}

}

</span>
```

```
<span style="font-family:SimHei;font-size:14px;">	public static void main(String[] args) throws InterruptedException {
		// create  a new thread from main thread
		Thread thread = new Thread(new HeavyRunnable());
		thread.start();
		Thread.sleep(2_000);
		thread.interrupt();		

	}</span>
```

执行heavyWork是一个比较费时的工作（注意这里循环次数一定要足够大，否则被中断之前它早就处理完了），每次调用这个费时的方法时，都检测一下当前是不是被中断了，如果中断，就返回。更复杂的应用中，我们也许不是简单地返回，而是抛出异常，然后在异常处理中做更复杂的工作。

```
<span style="font-family:SimHei;font-size:14px;">if (Thread.interrupted()) {
    throw new InterruptedException();
}</span>
```

中断状态标记：

线程中断机制是通过内部一个叫中断状态标记来实现的。如果调用静态方法Thread.interrupted()，这个标记被清零，但是如果调用实例方法isInterrupted()查询某个线程的状态，该线程的中断标记不会改变。看一下源码：

```
<span style="font-family:SimHei;font-size:14px;">  public boolean isInterrupted() {
        return isInterrupted(false);
    }</span>
```

```
<span style="font-family:SimHei;font-size:14px;"> public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }</span>
```

```
<span style="font-family:SimHei;font-size:14px;">    private native boolean isInterrupted(boolean ClearInterrupted);</span>
```

前两个方法都调用最后一个方法。最后的方法是个本地方法，它检测线程是否被中断，返回，并且根据参数决定是否将标记清零。实例方法isInterrupted（）只是查询是否中断，而不对标记为产生影响，即：

如果在查询之前为false，则返回false，并保持状态位不变还是false。

如果状态为查询之前为true，返回true，一样保持状态位为true。

而对于interrupted这个静态方法，情况不一样：

如果查询之前为false，则返回false，且保持false不变。

如果查询之前为true，则返回true，并且将状态标记清零，即变为false。

另外，抛出InterruptedException异常一般也将标记清零。

### 3.2.3 Join方法

实例方法用于等待某个线程完成。可以指定等待时间。如果join等待期间被中断，抛出InterruptedException。

```
<span style="font-family:SimHei;font-size:14px;">   public final synchronized void join(long millis)    throws InterruptedException
    public final synchronized void join(long millis, int nanos)    throws InterruptedException 
    public final void join() throws InterruptedException</span>
```

看一个例子：

```
<span style="font-family:SimHei;font-size:14px;">public class FirstRunnable implements Runnable {
	
	/*
	 * The code to be executed in a separately thread
	 */
	@Override
	public void run() {
		System.out.println("I am born from: "
				+ Thread.currentThread().getName());
		try {
			Thread.sleep(10_000);
		} catch (InterruptedException e) {
			System.out.println("Oh My God. I am interrupted!");
		}
		// 线程的静态方法都是针对当前线程的操作

	}

}

</span>
```

```
<span style="font-family:SimHei;font-size:14px;">public class JoinRunnable implements Runnable {

	private  Thread before;
	public JoinRunnable(Thread before) {
		this.before = before;
	}
	
	
	@Override
	public void run() {
		try {
			<span style="background-color: rgb(255, 255, 0);">before.join();</span>
		} catch (InterruptedException e) {
			System.out.println("I am interrupted while calling join()");
		}
		System.out.println("I am from" + Thread.currentThread().getName());

	}

}

</span>
```

在第二个Runnable中，我们调用了before线程的join，也就是等待before线程执行完之后再执行自己的代码。测试一下：

```
<span style="font-family:SimHei;font-size:14px;">	    public static void main(String[] args) {
		FirstRunnable runnable = new FirstRunnable();
		Thread thread = new Thread(runnable);
		thread.setName("Thread1");
		Thread thread2 = new Thread(new JoinRunnable(thread));
		thread2.setName("Thread2");
		thread.start();
		thread2.start();</span>
```

thread2的代码会在thread1执行完毕之后执行。输出：

```
<span style="font-family:SimHei;font-size:14px;">I am born from: Thread1
I am fromThread2
</span>
```

如果thread2在join等待期间没有被中断，它总是在thread1之后再执行。可是如果我们在主线程中断thread2，会抛出中断异常。加入一句thread2.interrupt()；此时thread2作为中断的响应，不再等待thread1，所以thread1和thread2执行顺序将无法预料，下面是可能的一种输出：

```
<span style="font-family:SimHei;font-size:14px;">I am interrupted while calling join()
I am fromThread2
I am born from: Thread1
</span>
```

3.2.4 其他一些方法：

有一个静态方法可以返回当前线程：

```
<span style="font-family:SimHei;font-size:14px;">public static Thread currentThread()</span>
```

所谓当前线程，就是执行你调用方法这行代码的线程。

```
<span style="font-family:SimHei;font-size:14px;">public static void dumpStack()</span>
```

打印线程的堆栈信息，即方法调用列表。详细的可以参考异常处理中的相关内容。

一些列get方法，返回相应的信息：

```
<span style="font-family:SimHei;font-size:14px;">public StackTraceElement[] getStackTrace() // 获取线程对象的堆栈信息
public long getId()                        // 获取线程ID
public Thread.State getState()             // 获取线程状态，返回类型为Thread内部定义的枚举类型
public final String getName()              // 返回线程名称
public final int getPriority()             // 返回线程优先级</span>
```

更多方法在线程组之后继续介绍。

# 4.线程同步

// 线程之间的通信一般通过共享域以及域所引用的对象，对于非原子的操作，可能导致数据不一致等问题，引入同步机制可以解决这些问题，但是同步机制有可能使得程序效率变低，甚至挂起。

## 4.1 多线程问题：不同步

对于一个简单的语句如：C++.这个自增的操作表面上看只需一步，但是被编译成字节码时，它需要多个步骤来完成：1）提取C的值；2）将C的值加1；3）将加1后的值存入C。现在考虑这样一种情况，有一个类Counter如下：

```
<span style="font-family:SimHei;font-size:14px;">class Counter {
    private int c = 0;

    public void increment() {
        c++;
    }

    public void decrement() {
        c--;
    }

    public int value() {
        return c;
    }

}</span>
```

如果两个或者多个线程共享这个类的某个对象，假设这个对象的C初值为0，比如有2个线程A和B，系统分配时间片为ABABAB，那么可能出现下列情况：

A：提取C值：0；

B：提取C值：0；

A：将C加一：1；

B：将C减一：-1；

A：存入C：1；

B：存入C：-1；

执行完之后，线程A以为C的值应该为1，可是实际上C的值被线程B覆盖了，变成-1，返回的值不是预期的值，这可能导致很严重的问题。为了更进一步理解这个问题，我们看一下具体的例子，假设我们有一个类Callme：

```
<span style="font-family:SimHei;font-size:14px;">/**
 * @author Brandon B. Lin
 *
 */
public class Callme {
	
	 void call(String msg) {
		System.out.print("[" + msg);
		try {
			// 调用该方法的线程sleep一秒
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			System.out.println("interrupted");
		}
		
		System.out.println("]");
	}

}
</span>
```

这个类只有一个简单的方法，输出一条消息，前后加上方括号。接着我们实现一个Runnable，在线程中访问Callme的对象：

```
<span style="font-family:SimHei;font-size:14px;">/**
 * @author Brandon B. Lin
 *
 */
public class UnCaller implements Runnable {

	private Callme target;
	private String msg;
	//constructor
	public UnCaller(Callme target, String msg) {
		this.target = target;
		this.msg = msg;
	}
	
	@Override
	public void run() {
		target.call(msg);

	}

}
</span>
```

最后我们创建三个线程，共享一个Callme对象：

```
<span style="font-family:SimHei;font-size:14px;">public class UnTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Callme call = new Callme();
		new Thread(new UnCaller(call, "Thread-1")).start();
		new Thread(new UnCaller(call, "Thread-2")).start();
		new Thread(new UnCaller(call, "Thread-3")).start();

	}

}
</span>
```

运行后可能的一种结果如下：

```
<span style="font-family:SimHei;font-size:14px;">[Thread-2[Thread-3[Thread-1]
]
]
</span>
```

这不是我们的本意。

为了解决这样的问题，Java提供了两种基本的机制来解决这一问题：同步方法和同步语句。

## 4.2 同步方法：

现在我们使用关键字synchronized把call方法声明为同步的：

```
<span style="font-family:SimHei;font-size:14px;">	synchronized void call(String msg) {
		System.out.print("[" + msg);
		try {
			// 调用该方法的线程sleep一秒
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			System.out.println("interrupted");
		}
		
		System.out.println("]");
	}</span>
```

再次运行程序，输出：

```
<span style="font-family:SimHei;font-size:14px;">[Thread-1]
[Thread-2]
[Thread-3]</span>
```

很好，如我们所愿。一个线程一旦获得同步方法的执行权，则其他任何线程想要调用该对象的所有同步方法都必须等待，可以这么理解，一个对象的所有同步方法拥有一把锁，当一个线程访问该对象的同步方法时，如果这把锁没有被其他线程拿走，则该线程拿走这把锁，然后执行同步方法，在同步方法结束之前，其他线程想要访问该对象的任何同步方法，都必须等待。方法返回时，线程也就交还这把锁，然后再给其他线程使用。因此第一个线程获取这把锁之后，完整输出内容，方法返回，交还锁，其他线程同样道理访问同步方法。

记住，一旦线程进入一个对象的同步方法，所有其他线程都不能再进入该对象的任何同步方法，但是仍然可以调用该对象的非同步方法，调用相同类的不同对象的方法更不用说了，没问题。另外，调用该类的静态同步方法也是没有问题的。

构造器不能使用synchronized关键字，否则会出现语法错误，构造器使用同步是没有意义的，因为没有创建对象之前，只有创建对象的线程有权利访问（执行）构造方法。

对于同步静态方法，synchronized锁住的是该类的所有的静态同步方法，对于非静态同步方法和其他非同步方法，都可以被其他线程正常调用。我们修改一下Callme类：

```
<span style="font-family:SimHei;font-size:14px;">public class Callme {
	
	 public synchronized void call(String msg) {
		System.out.print("[" + msg);
		try {
			// 调用该方法的线程sleep一秒
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			System.out.println("interrupted");
		}
		
		System.out.println("]");
	}
	 
	 public static synchronized void staticCall(String msg) {
		 System.out.print("static: [" + msg);
			try {
				// 调用该方法的线程sleep一秒
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				System.out.println("interrupted");
			}
			
			System.out.println("]");
	 }

}
</span>
```

然后一类线程访问实例同步方法：

```
<span style="font-family:SimHei;font-size:14px;">public class UnCaller implements Runnable {

	private Callme target;
	private String msg;
	//constructor
	public UnCaller(Callme target, String msg) {
		this.target = target;
		this.msg = msg;
	}
	
	@Override
	public void run() {
		target.call(msg);

	}

}
</span>
```

另一类线程访问同步静态方法：

```
<span style="font-family:SimHei;font-size:14px;">public class StaticCaller implements Runnable {

	private Callme target;
	private String msg;
	//constructor
	public StaticCaller(Callme target, String msg) {
		this.target = target;
		this.msg = msg;
	}
	
	@Override
	public void run() {
		target.staticCall(msg);

	}

}
</span>
```

再来测试一下：

```
<span style="font-family:SimHei;font-size:14px;">public class UnTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Callme call = new Callme();
		new Thread(new StaticCaller(call, "Thread-1")).start();
		new Thread(new StaticCaller(call, "Thread-2")).start();
		new Thread(new UnCaller(call, "Thread-3")).start();

	}

}
</span>
```

可能输出结果：

```
<span style="font-family:SimHei;font-size:14px;">static: [Thread-2[Thread-3]
static: [Thread-1]
]
</span>
```

可以看到synchronized对于静态和非静态方法限制不一样，同步的非静态方法锁住的是该对象的其他同步非静态方法，而同步静态方法锁住的是该类其他同步静态方法。总结一下如下表：

![](http://img.blog.csdn.net/20140606193804609)

也就是说，对于静态和同步这两个维度，锁住的是两个维度都相同的方法，比如，同步非静态锁住该对象其他所有同步非静态方法，而同步静态方法锁住该类其他所有同步静态方法。

## 4.3 synchronized语句：

如果我们要使用的类没有针对多线程进行设计，比如没有使用同步方法，且无法获取类的源代码（比如第三方类库），此时我们难道就无能为力了？不是的。我们把调用的代码放在synchronized代码块中。假设现在Callme类我们无法修改：

```
<span style="font-family:SimHei;font-size:14px;">	 public void call(String msg) {
		System.out.print("[" + msg);
		try {
			// 调用该方法的线程sleep一秒
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			System.out.println("interrupted");
		}
		
		System.out.println("]");
	}</span>
```

我们使用synchronized代码块来访问这个方法：

```
<span style="font-family:SimHei;font-size:14px;">	@Override
	public void run() {
		synchronized (target) {
			target.call(msg);
		}
	}</span>
```

达到的效果和使用同步方法是一样的。如果对静态方法使用同步块，synchronized语句中的参数不是类的对象，而是表示该类的Class对象。

下面两个例子达到的效果完全等同：

```
<span style="font-family:SimHei;font-size:14px;">class Test {
    int count;
    synchronized void bump(){
        count++;
    }
    static int classCount;
   static synchronized void classBump(){
        classCount++;
    }
}</span>
```

```
<span style="font-family:SimHei;font-size:14px;">class BumpTest {
    int count;
    void bump() {
       synchronized (this) { count++; }
    }
    static int classCount;
    static void classBump() {
        try {
            synchronized (Class.forName("BumpTest")) {
                classCount++;
            }
        } catch (ClassNotFoundException e) {}
    }
}</span>
```

# 5. 线程间通信

Java线程之间的通信的一种方式使用它们共用的对象的wait（）、notify（）、notifyAll（）方法。调用某个对象的wait方法，会使得当前线程挂起，直到有其他线程调用了该对象的notify或者notifyAll方法。生产者消费者的例子是最典型的例子：生产者只有在货物没有的时候才能生产，消费者只有在货物有的时候才能消费。为了避免出现消费者在没有货物的时候消费，或者生产者在还有货物的时候进行生产，生产和消费的线程必须实现通信，通过他们共同使用的“货物”对象实现通信。

我们先看一个最初的版本，首先定义表示货物的类：

```
<span style="font-family:SimHei;font-size:14px;">/**
 * @author Brandon B. Lin
 * 這個類用來表示貨物，貨物空了生產者才能放，有貨物消費者才能消費
 */
public class Goods {
	// 用於簡單表示貨物
	private String goods = "Nothing";
	private int remain = 0;  // 剩余的货物量
	
	// 生產者生產
	public synchronized void put(String goods) {
		// if empty ,then put
		this.goods = goods;
		remain++;
		System.out.println("I have put: " + goods +  " remaining:" + remain);
		
		
	}
	
	//消費者消費
	public synchronized void take() {
		// if any , take
		remain--;
		System.out.println("I have take: " + goods + " remaining:" + remain);
	}
	
	

}
</span>
```

然后定义消费者和生产者，为了模仿现实情况，我们给生产和消费都设置了一个随机的时间：

```
<span style="font-family:SimHei;font-size:14px;">import java.util.Random;

/**
 * @author Brandon B. Lin
 *
 */
public class Producer implements Runnable {

	private Goods goods;
	private Random random = new Random();
	
	
	public Producer(Goods goods) {
		this.goods = goods;
	}
	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			goods.put("goods " + i); //添加货物
			try {
				Thread.sleep(random.nextInt(10)*1_000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		

	}

}
</span>
```

```
<span style="font-family:SimHei;font-size:14px;">import java.util.Random;

/**
 * @author Brandon B. Lin
 *
 */

public class Consumer implements Runnable {

	private Goods goods;
	private Random random = new Random();
	
	
	public Consumer(Goods goods) {
		this.goods = goods;
	}
	@Override
	public void run() {
		for(int i = 0; i<10; i++) {
			goods.take(); // 取走货物
			try {
				Thread.sleep(random.nextInt(10)*1_000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
			
		}
		

	}
</span>
```

最后测试一下：

```
<span style="font-family:SimHei;font-size:14px;">/**
 * @author Brandon B. Lin
 *
 */
public class PC {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Goods g = new Goods();
		new Thread(new Producer(g)).start();
		new Thread(new Consumer(g)).start();

	}

}
</span>
```

可能输出像这样的情况：

```
<span style="font-family:SimHei;font-size:14px;">I have put: goods 0 remaining:1
I have put: goods 1 remaining:2
I have take: goods 1 remaining:1
I have put: goods 2 remaining:2
I have put: goods 3 remaining:3
I have put: goods 4 remaining:4
I have take: goods 4 remaining:3
I have take: goods 4 remaining:2
I have take: goods 4 remaining:1
I have take: goods 4 remaining:0
</span>
```

可以看到并不符合我们的要求，比如最开始连续放了两次货物。如果符合我们的要求，remain必须按照1，0，1，0，这样的顺序出现。为了实现这个目标，我们在生产者添加货物之后通知消费者，消费者拿走之后通知生产者，它们之间通过货物这个对象来实现。如果货物为空时，消费者必须等待，货物还有时，生产者必须等待。只需修改Goods这个类：

```
<span style="font-family:SimHei;font-size:14px;">/**
 * @author Brandon B. Lin
 * 這個類用來表示貨物，貨物空了生產者才能放，有貨物消費者才能消費
 */
public class Goods {
	// 用於簡單表示貨物
	private String goods = "Nothing";
	private int remain = 0;
	private boolean empty = true;
	
	// 生產者生產
	public synchronized void put(String goods) {
		// if empty ,then put ,or wait
		while (!empty) { // 如果货物不空 一直等待，直到得到其他线程的通知，这里指消费者的通知
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		this.goods = goods;
		empty = false;
		notifyAll(); // 添加货物之后，通知其他线程，这里指通知消费者
		remain++;
		System.out.println("I have put: " + goods +  " remaining:" + remain);
		
		
	}
	
	//消費者消費
	public synchronized void take() {
		// if any , take
		while (empty) { // 如果为空 等待 直到其他线程（这里指生产者）通知
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		remain--;
		empty = true;
		notifyAll(); //通知生产者货物已经拿走，好让它继续生产
		System.out.println("I have take: " + goods + " remaining:" + remain);
	}
	
	

}
</span>
```

此时输出为：

```
<span style="font-family:SimHei;font-size:14px;">I have put: goods 0 remaining:1
I have take: goods 0 remaining:0
I have put: goods 1 remaining:1
I have take: goods 1 remaining:0
I have put: goods 2 remaining:1
I have take: goods 2 remaining:0
I have put: goods 3 remaining:1
I have take: goods 3 remaining:0
I have put: goods 4 remaining:1
I have take: goods 4 remaining:0</span>
```

漂亮！生产者线程和消费者线程之间通过“货物”这个对象实现完美通信，具体通过wait，notify，notifyAll来实现，当然wait可以设定时间，比如超过5秒消费者就不等了。继续修改一下，假设现在有2个消费者，一旦有货物的时候，只能有一个消费者得到，另一个消费者继续等待。修改一下take（）方法的输出，输出货物是被谁取走的：

```
<span style="font-family:SimHei;font-size:14px;">//消費者消費
	public synchronized void take(String byWho) {
		// if any , take
		while (empty) {
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		remain--;
		empty = true;
		notifyAll();
		System.out.println(byWho + " have take: " + goods + " remaining:" + remain);
	}</span>
```

相应地在Consumer修改一下：

```
<span style="font-family:SimHei;font-size:14px;">public void run() {
		for(int i = 0; i<5; i++) {
			goods.take(Thread.currentThread().getName());
			try {
				Thread.sleep(random.nextInt(10)*1_000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
			
		}
		

	}</span>
```

然后再增加一个消费者：

```
<span style="font-family:SimHei;font-size:14px;">public static void main(String[] args) {
		Goods g = new Goods();
		new Thread(new Producer(g)).start();
		new Thread(new Consumer(g)).start();
		new Thread(new Consumer(g)).start();

	}</span>
```

可能的一种输出：

```
<span style="font-family:SimHei;font-size:14px;">I have put: goods 0 remaining:1
Thread-2 have take: goods 0 remaining:0
I have put: goods 1 remaining:1
Thread-1 have take: goods 1 remaining:0
I have put: goods 2 remaining:1
Thread-2 have take: goods 2 remaining:0
I have put: goods 3 remaining:1
Thread-1 have take: goods 3 remaining:0
I have put: goods 4 remaining:1
Thread-2 have take: goods 4 remaining:0
</span>
```

每次Producer生产一个货物，只有一个消费者可以获得，一样协调得很好，多亏了Java提供的这种通信方式。当然你可以再增加生产者，但无论添加多少个消费者和生产者，它们都不会乱套。

下面是一个更复杂的生产者，消费者模式：

```
<span style="font-family:SimHei;font-size:14px;">/**
 * 
 */
package threadTest.pc.complex;

/**
 * @author Brandon B. Lin
 *
 */
public class Product {
	private long id;
	private String type;
	private float price;
	
	public Product(long id) {
		this.id = id;
	}
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
	

}
</span>
```

```
<span style="font-family:SimHei;font-size:14px;">/**
 * 
 */
package threadTest.pc.complex;

import java.util.ArrayList;

/**
 * @author Brandon B. Lin
 *
 */
public class Storage {
	
	//倉庫最大存儲量
	private static final int MAX_SIZE = 20;
	// 存储货物
	ArrayList<Product> storage = new ArrayList<>();
	
	// 存入方法
	public synchronized void put(Product product, String byWho) {
		while(storage.size() >= MAX_SIZE) {
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		storage.add(product);
		System.out.println(byWho + " has put: " + product.getId() + " remaining: " + getSize());
		notifyAll();
	}
	
	// 存入方法
	public synchronized Product  take(String byWho) {
		while(storage.size() == 0) {
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Product p = storage.remove(0);
		notifyAll();
		System.out.println(byWho + " has taken: " + p.getId() + " remaining: " + getSize());
		return p;
	}
	
	// 查詢當前庫存
	public int getSize() {
		return storage.size();
	}
	

}
</span>
```

```
<span style="font-family:SimHei;font-size:14px;">/**
 * 
 */
package threadTest.pc.complex;

import java.util.Random;

/**
 * @author Brandon B. Lin
 *
 */
public class Producer implements Runnable {

	private Storage storage;
	private Random random = new Random();
	
	public Producer(Storage storage) {
		this.storage = storage;
	}
	
	
	@Override
	public void run() {
		long id = 1L;
		while (true) {
			Product p = new Product(id++);
			storage.put(p, Thread.currentThread().getName());
			try {
				Thread.sleep(random.nextInt(5)* 1_000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
	}

}
</span>
```

```
<span style="font-family:SimHei;font-size:14px;">/**
 * 
 */
package threadTest.pc.complex;

import java.util.Random;

/**
 * @author Brandon B. Lin
 *
 */
public class Consumer implements Runnable{
    private Storage storage;
    private Random random = new Random();
    
    public Consumer(Storage storage) {
    	this.storage = storage;
    }

	
	@Override
	public void run() {
		while (true) {
			storage.take(Thread.currentThread().getName());
			try {
				Thread.sleep(random.nextInt(5) * 1_000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
   
}
</span>
```

```
<span style="font-family:SimHei;font-size:14px;">/**
 * 
 */
package threadTest.pc.complex;

import threadTest.pc.complex.Consumer;;;

/**
 * @author Brandon B. Lin
 *
 */
public class PCTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Storage storage = new Storage();
		createNewThread(new Producer(storage), "Producter1");
		createNewThread(new Producer(storage), "Producter2");
		createNewThread(new Consumer(storage), "Consumer1");
		createNewThread(new Consumer(storage), "Consumer2");
	}
	
	private static void createNewThread(Runnable runnable, String name) {
		Thread thread = new Thread(runnable);
		thread.setName(name);
		thread.start();
	}

}
</span>
```

# 6. 死锁（Deadlock）

当两个线程循环依赖于一对同步对象时，会发生死锁。比如，线程A现在用于对象C的锁，线程B拥有对象D的锁，而线程A试图调用对象D中的其他同步方法，线程B也试图调用对象C的其他同步方法，此时就会陷入僵局，永远等下去。下面使用synchronized语句说明死锁：

```
/**
 * 
 */
package threadTest;

/**
 * @author Brandon B. Lin
 *
 */
public class DeadLock {
	   public static Object Lock1 = new Object();
	   public static Object Lock2 = new Object();
	   
	   public static void main(String args[]) {
	   
	      ThreadDemo1 T1 = new ThreadDemo1();
	      ThreadDemo2 T2 = new ThreadDemo2();
	      T1.start();
	      T2.start();
	   }
	   
	   private static class ThreadDemo1 extends Thread {
	      public void run() {
	         synchronized (Lock1) { // 线程1拥有对象Lock1的使用权
	            System.out.println("Thread 1: Holding lock 1...");
	            try { Thread.sleep(10); }
	            catch (InterruptedException e) {}
	            System.out.println("Thread 1: Waiting for lock 2...");
	            synchronized (Lock2) { // 试图使用Lock2
	               System.out.println("Thread 1: Holding lock 1 & 2...");
	            }
	         }
	      }
	   }
	   private static class ThreadDemo2 extends Thread {
	      public void run() {
	         synchronized (Lock2) {  // 线程2拥有对象Lock2的使用权
	            System.out.println("Thread 2: Holding lock 2...");
	            try { Thread.sleep(10); }
	            catch (InterruptedException e) {}
	            System.out.println("Thread 2: Waiting for lock 1...");
	            synchronized (Lock1) {  //试图使用Lock1
	               System.out.println("Thread 2: Holding lock 1 & 2...");
	            }
	         }
	      }
	   } 
	}
```

结果输出：

```
Thread 1: Holding lock 1...
Thread 2: Holding lock 2...
Thread 1: Waiting for lock 2...
Thread 2: Waiting for lock 1...
```

然后程序永远不会结束了，除非你强制关闭它。