多线程《转载》

特兹说明:转载自https://www.cnblogs.com/skywang12345/p/java_threads_category.html



多线程是Java中不可避免的一个重要主体。从本章开始,我们将展开对多线程的学习。接下来的内容,是对“JDK中新增JUC包”之前的Java多线程内容的讲解,涉及到的内容包括,Object类中的wait(), notify()等接口;Thread类中的接口;synchronized关键字。

注:JUC包是指,Java.util.concurrent包,它是由Java大师Doug Lea完成并在JDK1.5版本添加到Java中的。


在进入后面章节的学习之前,先对了解一些多线程的相关概念。
线程状态图

说明
线程共包括以下5种状态。
1. 新建状态(New)         : 线程对象被创建后,就进入了新建状态。例如,Thread thread = new Thread()。
2. 就绪状态(Runnable): 也被称为“可执行状态”。线程对象被创建后,其它线程调用了该对象的start()方法,从而来启动该线程。例如,thread.start()。处于就绪状态的线程,随时可能被CPU调度执行。
3. 运行状态(Running) : 线程获取CPU权限进行执行。需要注意的是,线程只能从就绪状态进入到运行状态。
4. 阻塞状态(Blocked)  : 阻塞状态是线程因为某种原因放弃CPU使用权,暂时停止运行。直到线程进入就绪状态,才有机会转到运行状态。阻塞的情况分三种:
    (01) 等待阻塞 -- 通过调用线程的wait()方法,让线程等待某工作的完成。
    (02) 同步阻塞 -- 线程在获取synchronized同步锁失败(因为锁被其它线程所占用),它会进入同步阻塞状态。
    (03) 其他阻塞 -- 通过调用线程的sleep()或join()或发出了I/O请求时,线程会进入到阻塞状态。当sleep()状态超时、join()等待线程终止或者超时、或者I/O处理完毕时,线程重新转入就绪状态。
5. 死亡状态(Dead)    : 线程执行完了或者因异常退出了run()方法,该线程结束生命周期。

 

这5种状态涉及到的内容包括Object类, Thread和synchronized关键字。这些内容我们会在后面的章节中逐个进行学习。
Object类,定义了wait(), notify(), notifyAll()等休眠/唤醒函数。
Thread类,定义了一些列的线程操作函数。例如,sleep()休眠函数, interrupt()中断函数, getName()获取线程名称等。
synchronized,是关键字;它区分为synchronized代码块和synchronized方法。synchronized的作用是让线程获取对象的同步锁。
在后面详细介绍wait(),notify()等方法时,我们会分析为什么“wait(), notify()等方法要定义在Object类,而不是Thread类中”。

概要

本章,我们学习“常用的实现多线程的2种方式”:Thread 和 Runnable
之所以说是常用的,是因为通过还可以通过java.util.concurrent包中的线程池来实现多线程。关于线程池的内容,我们以后会详细介绍;现在,先对的Thread和Runnable进行了解。本章内容包括:
Thread和Runnable的简介
Thread和Runnable的异同点
Thread和Runnable的多线程的示例

转载请注明出处:http://www.cnblogs.com/skywang12345/p/3479063.html

Thread和Runnable简介

Runnable 是一个接口,该接口中只包含了一个run()方法。它的定义如下:

public interface Runnable {
    public abstract void run();
}

Runnable的作用,实现多线程。我们可以定义一个类A实现Runnable接口;然后,通过new Thread(new A())等方式新建线程。

Thread 是一个类。Thread本身就实现了Runnable接口。它的声明如下:

public class Thread implements Runnable {}

Thread的作用,实现多线程。

Thread和Runnable的异同点

Thread 和 Runnable 的相同点都是“多线程的实现方式”。
Thread 和 Runnable 的不同点
Thread 是类,而Runnable是接口;Thread本身是实现了Runnable接口的类。我们知道“一个类只能有一个父类,但是却能实现多个接口”,因此Runnable具有更好的扩展性。
此外,Runnable还可以用于“资源的共享”。即,多个线程都是基于某一个Runnable对象建立的,它们会共享Runnable对象上的资源。
通常,建议通过“Runnable”实现多线程!

Thread和Runnable的多线程示例

1. Thread的多线程示例

下面通过示例更好的理解Thread和Runnable,借鉴网上一个例子比较具有说服性的例子。

复制代码
 1 // ThreadTest.java 源码
 2 class MyThread extends Thread{  
 3     private int ticket=10;  
 4     public void run(){
 5         for(int i=0;i<20;i++){ 
 6             if(this.ticket>0){
 7                 System.out.println(this.getName()+" 卖票:ticket"+this.ticket--);
 8             }
 9         }
10     } 
11 };
12 
13 public class ThreadTest {  
14     public static void main(String[] args) {  
15         // 启动3个线程t1,t2,t3;每个线程各卖10张票!
16         MyThread t1=new MyThread();
17         MyThread t2=new MyThread();
18         MyThread t3=new MyThread();
19         t1.start();
20         t2.start();
21         t3.start();
22     }  
23 } 
复制代码

运行结果

复制代码
Thread-0 卖票:ticket10
Thread-1 卖票:ticket10
Thread-2 卖票:ticket10
Thread-1 卖票:ticket9
Thread-0 卖票:ticket9
Thread-1 卖票:ticket8
Thread-2 卖票:ticket9
Thread-1 卖票:ticket7
Thread-0 卖票:ticket8
Thread-1 卖票:ticket6
Thread-2 卖票:ticket8
Thread-1 卖票:ticket5
Thread-0 卖票:ticket7
Thread-1 卖票:ticket4
Thread-2 卖票:ticket7
Thread-1 卖票:ticket3
Thread-0 卖票:ticket6
Thread-1 卖票:ticket2
Thread-2 卖票:ticket6
Thread-2 卖票:ticket5
Thread-2 卖票:ticket4
Thread-1 卖票:ticket1
Thread-0 卖票:ticket5
Thread-2 卖票:ticket3
Thread-0 卖票:ticket4
Thread-2 卖票:ticket2
Thread-0 卖票:ticket3
Thread-2 卖票:ticket1
Thread-0 卖票:ticket2
Thread-0 卖票:ticket1
复制代码

结果说明
(01) MyThread继承于Thread,它是自定义个线程。每个MyThread都会卖出10张票。
(02) 主线程main创建并启动3个MyThread子线程。每个子线程都各自卖出了10张票。

2. Runnable的多线程示例

下面,我们对上面的程序进行修改。通过Runnable实现一个接口,从而实现多线程。

复制代码
 1 // RunnableTest.java 源码
 2 class MyThread implements Runnable{  
 3     private int ticket=10;  
 4     public void run(){
 5         for(int i=0;i<20;i++){ 
 6             if(this.ticket>0){
 7                 System.out.println(Thread.currentThread().getName()+" 卖票:ticket"+this.ticket--);
 8             }
 9         }
10     } 
11 }; 
12 
13 public class RunnableTest {  
14     public static void main(String[] args) {  
15         MyThread mt=new MyThread();
16 
17         // 启动3个线程t1,t2,t3(它们共用一个Runnable对象),这3个线程一共卖10张票!
18         Thread t1=new Thread(mt);
19         Thread t2=new Thread(mt);
20         Thread t3=new Thread(mt);
21         t1.start();
22         t2.start();
23         t3.start();
24     }  
25 }
复制代码

运行结果

复制代码
Thread-0 卖票:ticket10
Thread-2 卖票:ticket8
Thread-1 卖票:ticket9
Thread-2 卖票:ticket6
Thread-0 卖票:ticket7
Thread-2 卖票:ticket4
Thread-1 卖票:ticket5
Thread-2 卖票:ticket2
Thread-0 卖票:ticket3
Thread-1 卖票:ticket1
复制代码

结果说明
(01) 和上面“MyThread继承于Thread”不同;这里的MyThread实现了Thread接口。
(02) 主线程main创建并启动3个子线程,而且这3个子线程都是基于“mt这个Runnable对象”而创建的。运行结果是这3个子线程一共卖出了10张票。这说明它们是共享了MyThread接口的。

概要

Thread类包含start()和run()方法,它们的区别是什么?本章将对此作出解答。本章内容包括:
start() 和 run()的区别说明
start() 和 run()的区别示例
start() 和 run()相关源码(基于JDK1.7.0_40)

转载请注明出处:http://www.cnblogs.com/skywang12345/p/3479083.html

start() 和 run()的区别说明

start() : 它的作用是启动一个新线程,新线程会执行相应的run()方法。start()不能被重复调用。
run()   : run()就和普通的成员方法一样,可以被重复调用。单独调用run()的话,会在当前线程中执行run(),而并不会启动新线程!

下面以代码来进行说明。

class MyThread extends Thread{  
    public void run(){
        ...
    } 
};
MyThread mythread = new MyThread();

mythread.start()会启动一个新线程,并在新线程中运行run()方法。
而mythread.run()则会直接在当前线程中运行run()方法,并不会启动一个新线程来运行run()。

start() 和 run()的区别示例

下面,通过一个简单示例演示它们之间的区别。源码如下:

复制代码
 1 // Demo.java 的源码
 2 class MyThread extends Thread{  
 3     public MyThread(String name) {
 4         super(name);
 5     }
 6 
 7     public void run(){
 8         System.out.println(Thread.currentThread().getName()+" is running");
 9     } 
10 }; 
11 
12 public class Demo {  
13     public static void main(String[] args) {  
14         Thread mythread=new MyThread("mythread");
15 
16         System.out.println(Thread.currentThread().getName()+" call mythread.run()");
17         mythread.run();
18 
19         System.out.println(Thread.currentThread().getName()+" call mythread.start()");
20         mythread.start();
21     }  
22 }
复制代码

运行结果

main call mythread.run()
main is running
main call mythread.start()
mythread is running

结果说明
(01) Thread.currentThread().getName()是用于获取“当前线程”的名字。当前线程是指正在cpu中调度执行的线程。
(02) mythread.run()是在“主线程main”中调用的,该run()方法直接运行在“主线程main”上。
(03) mythread.start()会启动“线程mythread”,“线程mythread”启动之后,会调用run()方法;此时的run()方法是运行在“线程mythread”上。

start() 和 run()相关源码(基于JDK1.7.0_40)

Thread.java中start()方法的源码如下:

复制代码
public synchronized void start() {
    // 如果线程不是"就绪状态",则抛出异常!
    if (threadStatus != 0)
        throw new IllegalThreadStateException();

    // 将线程添加到ThreadGroup中
    group.add(this);

    boolean started = false;
    try {
        // 通过start0()启动线程
        start0();
        // 设置started标记
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
        }
    }
}
复制代码

说明:start()实际上是通过本地方法start0()启动线程的。而start0()会新运行一个线程,新线程会调用run()方法。

private native void start0();

Thread.java中run()的代码如下:

public void run() {
    if (target != null) {
        target.run();
    }
}

说明:target是一个Runnable对象。run()就是直接调用Thread线程的Runnable成员的run()方法,并不会新建一个线程。

概要

本章,会对synchronized关键字进行介绍。涉及到的内容包括:
1. synchronized原理
2. synchronized基本规则
3. synchronized方法 和 synchronized代码块
4. 实例锁 和 全局锁

转载请注明出处:http://www.cnblogs.com/skywang12345/p/3479202.html

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代码块”的访问将被阻塞。

第一条

当一个线程访问“某对象”的“synchronized方法”或者“synchronized代码块”时,其他线程对“该对象”的该“synchronized方法”或者“synchronized代码块”的访问将被阻塞。
下面是“synchronized代码块”对应的演示程序。

复制代码
 1 class MyRunable implements Runnable {
 2     
 3     @Override
 4     public void run() {
 5         synchronized(this) {
 6             try {  
 7                 for (int i = 0; i < 5; i++) {
 8                     Thread.sleep(100); // 休眠100ms
 9                     System.out.println(Thread.currentThread().getName() + " loop " + i);  
10                 }
11             } catch (InterruptedException ie) {  
12             }
13         }  
14     }
15 }
16 
17 public class Demo1_1 {
18 
19     public static void main(String[] args) {  
20         Runnable demo = new MyRunable();     // 新建“Runnable对象”
21 
22         Thread t1 = new Thread(demo, "t1");  // 新建“线程t1”, t1是基于demo这个Runnable对象
23         Thread t2 = new Thread(demo, "t2");  // 新建“线程t2”, t2是基于demo这个Runnable对象
24         t1.start();                          // 启动“线程t1”
25         t2.start();                          // 启动“线程t2” 
26     } 
27 }
复制代码

运行结果

复制代码
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的同步锁”之后才能运行。

如果你确认,你搞清楚这个问题了。那我们将上面的代码进行修改,然后再运行看看结果怎么样,看看你是否会迷糊。修改后的源码如下:

复制代码
 1 class MyThread extends Thread {
 2     
 3     public MyThread(String name) {
 4         super(name);
 5     }
 6 
 7     @Override
 8     public void run() {
 9         synchronized(this) {
10             try {  
11                 for (int i = 0; i < 5; i++) {
12                     Thread.sleep(100); // 休眠100ms
13                     System.out.println(Thread.currentThread().getName() + " loop " + i);  
14                 }
15             } catch (InterruptedException ie) {  
16             }
17         }  
18     }
19 }
20 
21 public class Demo1_2 {
22 
23     public static void main(String[] args) {  
24         Thread t1 = new MyThread("t1");  // 新建“线程t1”
25         Thread t2 = new MyThread("t2");  // 新建“线程t2”
26         t1.start();                          // 启动“线程t1”
27         t2.start();                          // 启动“线程t2” 
28     } 
29 }
复制代码

代码说明
比较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对象,因此,一个线程获取了对象的同步锁,会造成另外一个线程等待。

第二条

当一个线程访问“某对象”的“synchronized方法”或者“synchronized代码块”时,其他线程仍然可以访问“该对象”的非同步代码块。
下面是“synchronized代码块”对应的演示程序。

复制代码
 1 class Count {
 2 
 3     // 含有synchronized同步块的方法
 4     public void synMethod() {
 5         synchronized(this) {
 6             try {  
 7                 for (int i = 0; i < 5; i++) {
 8                     Thread.sleep(100); // 休眠100ms
 9                     System.out.println(Thread.currentThread().getName() + " synMethod loop " + i);  
10                 }
11             } catch (InterruptedException ie) {  
12             }
13         }  
14     }
15 
16     // 非同步的方法
17     public void nonSynMethod() {
18         try {  
19             for (int i = 0; i < 5; i++) {
20                 Thread.sleep(100);
21                 System.out.println(Thread.currentThread().getName() + " nonSynMethod loop " + i);  
22             }
23         } catch (InterruptedException ie) {  
24         }
25     }
26 }
27 
28 public class Demo2 {
29 
30     public static void main(String[] args) {  
31         final Count count = new Count();
32         // 新建t1, t1会调用“count对象”的synMethod()方法
33         Thread t1 = new Thread(
34                 new Runnable() {
35                     @Override
36                     public void run() {
37                         count.synMethod();
38                     }
39                 }, "t1");
40 
41         // 新建t2, t2会调用“count对象”的nonSynMethod()方法
42         Thread t2 = new Thread(
43                 new Runnable() {
44                     @Override
45                     public void run() {
46                         count.nonSynMethod();
47                     }
48                 }, "t2");  
49 
50 
51         t1.start();  // 启动t1
52         t2.start();  // 启动t2
53     } 
54 }
复制代码

运行结果

复制代码
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”同步锁。

第三条

当一个线程访问“某对象”的“synchronized方法”或者“synchronized代码块”时,其他线程对“该对象”的其他的“synchronized方法”或者“synchronized代码块”的访问将被阻塞。
我们将上面的例子中的nonSynMethod()方法体的也用synchronized(this)修饰。修改后的源码如下:

复制代码
 1 class Count {
 2 
 3     // 含有synchronized同步块的方法
 4     public void synMethod() {
 5         synchronized(this) {
 6             try {  
 7                 for (int i = 0; i < 5; i++) {
 8                     Thread.sleep(100); // 休眠100ms
 9                     System.out.println(Thread.currentThread().getName() + " synMethod loop " + i);  
10                 }
11             } catch (InterruptedException ie) {  
12             }
13         }  
14     }
15 
16     // 也包含synchronized同步块的方法
17     public void nonSynMethod() {
18         synchronized(this) {
19             try {  
20                 for (int i = 0; i < 5; i++) {
21                     Thread.sleep(100);
22                     System.out.println(Thread.currentThread().getName() + " nonSynMethod loop " + i);  
23                 }
24             } catch (InterruptedException ie) {  
25             }
26         }
27     }
28 }
29 
30 public class Demo3 {
31 
32     public static void main(String[] args) {  
33         final Count count = new Count();
34         // 新建t1, t1会调用“count对象”的synMethod()方法
35         Thread t1 = new Thread(
36                 new Runnable() {
37                     @Override
38                     public void run() {
39                         count.synMethod();
40                     }
41                 }, "t1");
42 
43         // 新建t2, t2会调用“count对象”的nonSynMethod()方法
44         Thread t2 = new Thread(
45                 new Runnable() {
46                     @Override
47                     public void run() {
48                         count.nonSynMethod();
49                     }
50                 }, "t2");  
51 
52 
53         t1.start();  // 启动t1
54         t2.start();  // 启动t2
55     } 
56 }
复制代码

运行结果

复制代码
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代码块可以更精确的控制冲突限制访问区域,有时候表现更高效率。下面通过一个示例来演示:

复制代码
 1 // Demo4.java的源码
 2 public class Demo4 {
 3 
 4     public synchronized void synMethod() {
 5         for(int i=0; i<1000000; i++)
 6             ;
 7     }
 8 
 9     public void synBlock() {
10         synchronized( this ) {
11             for(int i=0; i<1000000; i++)
12                 ;
13         }
14     }
15 
16     public static void main(String[] args) {
17         Demo4 demo = new Demo4();
18 
19         long start, diff;
20         start = System.currentTimeMillis();                // 获取当前时间(millis)
21         demo.synMethod();                                // 调用“synchronized方法”
22         diff = System.currentTimeMillis() - start;        // 获取“时间差值”
23         System.out.println("synMethod() : "+ diff);
24         
25         start = System.currentTimeMillis();                // 获取当前时间(millis)
26         demo.synBlock();                                // 调用“synchronized方法块”
27         diff = System.currentTimeMillis() - start;        // 获取“时间差值”
28         System.out.println("synBlock()  : "+ diff);
29     }
30 }
复制代码

(某一次)执行结果

synMethod() : 11
synBlock() : 3

4. 实例锁 和 全局锁

实例锁 -- 锁在某一个实例对象上。如果该类是单例,那么该锁也具有全局锁的概念。
               实例锁对应的就是synchronized关键字。
全局锁 -- 该锁针对的是类,无论实例多少个对象,那么线程都共享该锁。
               全局锁对应的就是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组表达式获取的锁的情况。
(01) x.isSyncA()与x.isSyncB() 
(02) x.isSyncA()与y.isSyncA()
(03) x.cSyncA()与y.cSyncB()
(04) x.isSyncA()与Something.cSyncA()

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

复制代码
 1 // LockTest1.java的源码
 2 class Something {
 3     public synchronized void isSyncA(){
 4         try {  
 5             for (int i = 0; i < 5; i++) {
 6                 Thread.sleep(100); // 休眠100ms
 7                 System.out.println(Thread.currentThread().getName()+" : isSyncA");
 8             }
 9         }catch (InterruptedException ie) {  
10         }  
11     }
12     public synchronized void isSyncB(){
13         try {  
14             for (int i = 0; i < 5; i++) {
15                 Thread.sleep(100); // 休眠100ms
16                 System.out.println(Thread.currentThread().getName()+" : isSyncB");
17             }
18         }catch (InterruptedException ie) {  
19         }  
20     }
21 }
22 
23 public class LockTest1 {
24 
25     Something x = new Something();
26     Something y = new Something();
27 
28     // 比较(01) x.isSyncA()与x.isSyncB() 
29     private void test1() {
30         // 新建t11, t11会调用 x.isSyncA()
31         Thread t11 = new Thread(
32                 new Runnable() {
33                     @Override
34                     public void run() {
35                         x.isSyncA();
36                     }
37                 }, "t11");
38 
39         // 新建t12, t12会调用 x.isSyncB()
40         Thread t12 = new Thread(
41                 new Runnable() {
42                     @Override
43                     public void run() {
44                         x.isSyncB();
45                     }
46                 }, "t12");  
47 
48 
49         t11.start();  // 启动t11
50         t12.start();  // 启动t12
51     }
52 
53     public static void main(String[] args) {
54         LockTest1 demo = new LockTest1();
55         demo.test1();
56     }
57 }
复制代码

运行结果

复制代码
t11 : isSyncA
t11 : isSyncA
t11 : isSyncA
t11 : isSyncA
t11 : isSyncA
t12 : isSyncB
t12 : isSyncB
t12 : isSyncB
t12 : isSyncB
t12 : isSyncB
复制代码

(02) 可以同时被访问。因为访问的不是同一个对象的同步锁,x.isSyncA()访问的是x的同步锁,而y.isSyncA()访问的是y的同步锁。

复制代码
 1 // LockTest2.java的源码
 2 class Something {
 3     public synchronized void isSyncA(){
 4         try {  
 5             for (int i = 0; i < 5; i++) {
 6                 Thread.sleep(100); // 休眠100ms
 7                 System.out.println(Thread.currentThread().getName()+" : isSyncA");
 8             }
 9         }catch (InterruptedException ie) {  
10         }  
11     }
12     public synchronized void isSyncB(){
13         try {  
14             for (int i = 0; i < 5; i++) {
15                 Thread.sleep(100); // 休眠100ms
16                 System.out.println(Thread.currentThread().getName()+" : isSyncB");
17             }
18         }catch (InterruptedException ie) {  
19         }  
20     }
21     public static synchronized void cSyncA(){
22         try {  
23             for (int i = 0; i < 5; i++) {
24                 Thread.sleep(100); // 休眠100ms
25                 System.out.println(Thread.currentThread().getName()+" : cSyncA");
26             } 
27         }catch (InterruptedException ie) {  
28         }  
29     }
30     public static synchronized void cSyncB(){
31         try {  
32             for (int i = 0; i < 5; i++) {
33                 Thread.sleep(100); // 休眠100ms
34                 System.out.println(Thread.currentThread().getName()+" : cSyncB");
35             } 
36         }catch (InterruptedException ie) {  
37         }  
38     }
39 }
40 
41 public class LockTest2 {
42 
43     Something x = new Something();
44     Something y = new Something();
45 
46     // 比较(02) x.isSyncA()与y.isSyncA()
47     private void test2() {
48         // 新建t21, t21会调用 x.isSyncA()
49         Thread t21 = new Thread(
50                 new Runnable() {
51                     @Override
52                     public void run() {
53                         x.isSyncA();
54                     }
55                 }, "t21");
56 
57         // 新建t22, t22会调用 x.isSyncB()
58         Thread t22 = new Thread(
59                 new Runnable() {
60                     @Override
61                     public void run() {
62                         y.isSyncA();
63                     }
64                 }, "t22");  
65 
66 
67         t21.start();  // 启动t21
68         t22.start();  // 启动t22
69     }
70 
71     public static void main(String[] args) {
72         LockTest2 demo = new LockTest2();
73 
74         demo.test2();
75     }
76 }
复制代码

运行结果

复制代码
t21 : isSyncA
t22 : isSyncA
t21 : isSyncA
t22 : isSyncA
t21 : isSyncA
t22 : isSyncA
t21 : isSyncA
t22 : isSyncA
t21 : isSyncA
t22 : isSyncA
复制代码

(03) 不能被同时访问。因为cSyncA()和cSyncB()都是static类型,x.cSyncA()相当于Something.isSyncA(),y.cSyncB()相当于Something.isSyncB(),因此它们共用一个同步锁,不能被同时反问。

复制代码
 1 // LockTest3.java的源码
 2 class Something {
 3     public synchronized void isSyncA(){
 4         try {  
 5             for (int i = 0; i < 5; i++) {
 6                 Thread.sleep(100); // 休眠100ms
 7                 System.out.println(Thread.currentThread().getName()+" : isSyncA");
 8             }
 9         }catch (InterruptedException ie) {  
10         }  
11     }
12     public synchronized void isSyncB(){
13         try {  
14             for (int i = 0; i < 5; i++) {
15                 Thread.sleep(100); // 休眠100ms
16                 System.out.println(Thread.currentThread().getName()+" : isSyncB");
17             }
18         }catch (InterruptedException ie) {  
19         }  
20     }
21     public static synchronized void cSyncA(){
22         try {  
23             for (int i = 0; i < 5; i++) {
24                 Thread.sleep(100); // 休眠100ms
25                 System.out.println(Thread.currentThread().getName()+" : cSyncA");
26             } 
27         }catch (InterruptedException ie) {  
28         }  
29     }
30     public static synchronized void cSyncB(){
31         try {  
32             for (int i = 0; i < 5; i++) {
33                 Thread.sleep(100); // 休眠100ms
34                 System.out.println(Thread.currentThread().getName()+" : cSyncB");
35             } 
36         }catch (InterruptedException ie) {  
37         }  
38     }
39 }
40 
41 public class LockTest3 {
42 
43     Something x = new Something();
44     Something y = new Something();
45 
46     // 比较(03) x.cSyncA()与y.cSyncB()
47     private void test3() {
48         // 新建t31, t31会调用 x.isSyncA()
49         Thread t31 = new Thread(
50                 new Runnable() {
51                     @Override
52                     public void run() {
53                         x.cSyncA();
54                     }
55                 }, "t31");
56 
57         // 新建t32, t32会调用 x.isSyncB()
58         Thread t32 = new Thread(
59                 new Runnable() {
60                     @Override
61                     public void run() {
62                         y.cSyncB();
63                     }
64                 }, "t32");  
65 
66 
67         t31.start();  // 启动t31
68         t32.start();  // 启动t32
69     }
70 
71     public static void main(String[] args) {
72         LockTest3 demo = new LockTest3();
73 
74         demo.test3();
75     }
76 }
复制代码

运行结果

复制代码
t31 : cSyncA
t31 : cSyncA
t31 : cSyncA
t31 : cSyncA
t31 : cSyncA
t32 : cSyncB
t32 : cSyncB
t32 : cSyncB
t32 : cSyncB
t32 : cSyncB
复制代码

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

复制代码
 1 // LockTest4.java的源码
 2 class Something {
 3     public synchronized void isSyncA(){
 4         try {  
 5             for (int i = 0; i < 5; i++) {
 6                 Thread.sleep(100); // 休眠100ms
 7                 System.out.println(Thread.currentThread().getName()+" : isSyncA");
 8             }
 9         }catch (InterruptedException ie) {  
10         }  
11     }
12     public synchronized void isSyncB(){
13         try {  
14             for (int i = 0; i < 5; i++) {
15                 Thread.sleep(100); // 休眠100ms
16                 System.out.println(Thread.currentThread().getName()+" : isSyncB");
17             }
18         }catch (InterruptedException ie) {  
19         }  
20     }
21     public static synchronized void cSyncA(){
22         try {  
23             for (int i = 0; i < 5; i++) {
24                 Thread.sleep(100); // 休眠100ms
25                 System.out.println(Thread.currentThread().getName()+" : cSyncA");
26             } 
27         }catch (InterruptedException ie) {  
28         }  
29     }
30     public static synchronized void cSyncB(){
31         try {  
32             for (int i = 0; i < 5; i++) {
33                 Thread.sleep(100); // 休眠100ms
34                 System.out.println(Thread.currentThread().getName()+" : cSyncB");
35             } 
36         }catch (InterruptedException ie) {  
37         }  
38     }
39 }
40 
41 public class LockTest4 {
42 
43     Something x = new Something();
44     Something y = new Something();
45 
46     // 比较(04) x.isSyncA()与Something.cSyncA()
47     private void test4() {
48         // 新建t41, t41会调用 x.isSyncA()
49         Thread t41 = new Thread(
50                 new Runnable() {
51                     @Override
52                     public void run() {
53                         x.isSyncA();
54                     }
55                 }, "t41");
56 
57         // 新建t42, t42会调用 x.isSyncB()
58         Thread t42 = new Thread(
59                 new Runnable() {
60                     @Override
61                     public void run() {
62                         Something.cSyncA();
63                     }
64                 }, "t42");  
65 
66 
67         t41.start();  // 启动t41
68         t42.start();  // 启动t42
69     }
70 
71     public static void main(String[] args) {
72         LockTest4 demo = new LockTest4();
73 
74         demo.test4();
75     }
76 }
复制代码

运行结果

复制代码
t41 : isSyncA
t42 : cSyncA
t41 : isSyncA
t42 : cSyncA
t41 : isSyncA
t42 : cSyncA
t41 : isSyncA
t42 : cSyncA
t41 : isSyncA
t42 : cSyncA

概要

本章,会对线程等待/唤醒方法进行介绍。涉及到的内容包括:
1. wait(), notify(), notifyAll()等方法介绍
2. wait()和notify()
3. wait(long timeout)和notify()
4. wait() 和 notifyAll()
5. 为什么notify(), wait()等函数定义在Object中,而不是Thread中

转载请注明出处:http://www.cnblogs.com/skywang12345/p/3479224.html

wait(), notify(), notifyAll()等方法介绍

在Object.java中,定义了wait(), notify()和notifyAll()等接口。wait()的作用是让当前线程进入等待状态,同时,wait()也会让当前线程释放它所持有的锁。而notify()和notifyAll()的作用,则是唤醒当前对象上的等待线程;notify()是唤醒单个线程,而notifyAll()是唤醒所有的线程。

Object类中关于等待/唤醒的API详细信息如下:
notify()        -- 唤醒在此对象监视器上等待的单个线程。
notifyAll()   -- 唤醒在此对象监视器上等待的所有线程。
wait()                                         -- 让当前线程处于“等待(阻塞)状态”,“直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法”,当前线程被唤醒(进入“就绪状态”)。
wait(long timeout)                    -- 让当前线程处于“等待(阻塞)状态”,“直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者超过指定的时间量”,当前线程被唤醒(进入“就绪状态”)。
wait(long timeout, int nanos)  -- 让当前线程处于“等待(阻塞)状态”,“直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者其他某个线程中断当前线程,或者已超过某个实际时间量”,当前线程被唤醒(进入“就绪状态”)。

2. wait()和notify()示例

下面通过示例演示"wait()和notify()配合使用的情形"。

复制代码
// WaitTest.java的源码
class ThreadA extends Thread{

    public ThreadA(String name) {
        super(name);
    }

    public void run() {
        synchronized (this) {
            System.out.println(Thread.currentThread().getName()+" call notify()");
            // 唤醒当前的wait线程
            notify();
        }
    }
}

public class WaitTest {

    public static void main(String[] args) {

        ThreadA t1 = new ThreadA("t1");

        synchronized(t1) {
            try {
                // 启动“线程t1”
                System.out.println(Thread.currentThread().getName()+" start t1");
                t1.start();

                // 主线程等待t1通过notify()唤醒。
                System.out.println(Thread.currentThread().getName()+" wait()");
                t1.wait();

                System.out.println(Thread.currentThread().getName()+" continue");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
复制代码

运行结果:

main start t1
main wait()
t1 call notify()
main continue

结果说明
如下图,说明了“主线程”和“线程t1”的流程。

(01) 注意,图中"主线程" 代表“主线程main”。"线程t1" 代表WaitTest中启动的“线程t1”。 而“锁” 代表“t1这个对象的同步锁”。
(02) “主线程”通过 new ThreadA("t1") 新建“线程t1”。随后通过synchronized(t1)获取“t1对象的同步锁”。然后调用t1.start()启动“线程t1”。
(03) “主线程”执行t1.wait() 释放“t1对象的锁”并且进入“等待(阻塞)状态”。等待t1对象上的线程通过notify() 或 notifyAll()将其唤醒。
(04) “线程t1”运行之后,通过synchronized(this)获取“当前对象的锁”;接着调用notify()唤醒“当前对象上的等待线程”,也就是唤醒“主线程”。
(05) “线程t1”运行完毕之后,释放“当前对象的锁”。紧接着,“主线程”获取“t1对象的锁”,然后接着运行。

对于上面的代码?曾经有个朋友问到过:t1.wait()应该是让“线程t1”等待;但是,为什么却是让“主线程main”等待了呢?
在解答该问题前,我们先看看jdk文档中关于wait的一段介绍:

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. 
In other words, this method behaves exactly as if it simply performs the call wait(0).
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

中文意思大概是:

引起“当前线程”等待,直到另外一个线程调用notify()或notifyAll()唤醒该线程。换句话说,这个方法和wait(0)的效果一样!(补充,对于wait(long millis)方法,当millis为0时,表示无限等待,直到被notify()或notifyAll()唤醒)。
“当前线程”在调用wait()时,必须拥有该对象的同步锁。该线程调用wait()之后,会释放该锁;然后一直等待直到“其它线程”调用对象的同步锁的notify()或notifyAll()方法。然后,该线程继续等待直到它重新获取“该对象的同步锁”,然后就可以接着运行。

注意:jdk的解释中,说wait()的作用是让“当前线程”等待,而“当前线程”是指正在cpu上运行的线程!
这也意味着,虽然t1.wait()是通过“线程t1”调用的wait()方法,但是调用t1.wait()的地方是在“主线程main”中。而主线程必须是“当前线程”,也就是运行状态,才可以执行t1.wait()。所以,此时的“当前线程”是“主线程main”!因此,t1.wait()是让“主线程”等待,而不是“线程t1”!

3. wait(long timeout)和notify()

wait(long timeout)会让当前线程处于“等待(阻塞)状态”,“直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者超过指定的时间量”,当前线程被唤醒(进入“就绪状态”)。
下面的示例就是演示wait(long timeout)在超时情况下,线程被唤醒的情况。

复制代码
// WaitTimeoutTest.java的源码
class ThreadA extends Thread{

    public ThreadA(String name) {
        super(name);
    }

    public void run() {
        System.out.println(Thread.currentThread().getName() + " run ");
        // 死循环,不断运行。
        while(true)
            ;
    }
}

public class WaitTimeoutTest {

    public static void main(String[] args) {

        ThreadA t1 = new ThreadA("t1");

        synchronized(t1) {
            try {
                // 启动“线程t1”
                System.out.println(Thread.currentThread().getName() + " start t1");
                t1.start();

                // 主线程等待t1通过notify()唤醒 或 notifyAll()唤醒,或超过3000ms延时;然后才被唤醒。
                System.out.println(Thread.currentThread().getName() + " call wait ");
                t1.wait(3000);

                System.out.println(Thread.currentThread().getName() + " continue");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
复制代码

运行结果

main start t1
main call wait 
t1 run                  // 大约3秒之后...输出“main continue”
main continue

结果说明
如下图,说明了“主线程”和“线程t1”的流程。
(01) 注意,图中"主线程" 代表WaitTimeoutTest主线程(即,线程main)。"线程t1" 代表WaitTest中启动的线程t1。 而“锁” 代表“t1这个对象的同步锁”。
(02) 主线程main执行t1.start()启动“线程t1”。
(03) 主线程main执行t1.wait(3000),此时,主线程进入“阻塞状态”。需要“用于t1对象锁的线程通过notify() 或者 notifyAll()将其唤醒” 或者 “超时3000ms之后”,主线程main才进入到“就绪状态”,然后才可以运行。
(04) “线程t1”运行之后,进入了死循环,一直不断的运行。
(05) 超时3000ms之后,主线程main会进入到“就绪状态”,然后接着进入“运行状态”。

 

4. wait() 和 notifyAll()

通过前面的示例,我们知道 notify() 可以唤醒在此对象监视器上等待的单个线程。
下面,我们通过示例演示notifyAll()的用法;它的作用是唤醒在此对象监视器上等待的所有线程。

复制代码
 1 public class NotifyAllTest {
 2 
 3     private static Object obj = new Object();
 4     public static void main(String[] args) {
 5 
 6         ThreadA t1 = new ThreadA("t1");
 7         ThreadA t2 = new ThreadA("t2");
 8         ThreadA t3 = new ThreadA("t3");
 9         t1.start();
10         t2.start();
11         t3.start();
12 
13         try {
14             System.out.println(Thread.currentThread().getName()+" sleep(3000)");
15             Thread.sleep(3000);
16         } catch (InterruptedException e) {
17             e.printStackTrace();
18         }
19 
20         synchronized(obj) {
21             // 主线程等待唤醒。
22             System.out.println(Thread.currentThread().getName()+" notifyAll()");
23             obj.notifyAll();
24         }
25     }
26 
27     static class ThreadA extends Thread{
28 
29         public ThreadA(String name){
30             super(name);
31         }
32 
33         public void run() {
34             synchronized (obj) {
35                 try {
36                     // 打印输出结果
37                     System.out.println(Thread.currentThread().getName() + " wait");
38 
39                     // 唤醒当前的wait线程
40                     obj.wait();
41 
42                     // 打印输出结果
43                     System.out.println(Thread.currentThread().getName() + " continue");
44                 } catch (InterruptedException e) {
45                     e.printStackTrace();
46                 }
47             }
48         }
49     }
50 }
复制代码

运行结果

复制代码
t1 wait
main sleep(3000)
t3 wait
t2 wait
main notifyAll()
t2 continue
t3 continue
t1 continue
复制代码

结果说明
参考下面的流程图。 
(01) 主线程中新建并且启动了3个线程"t1", "t2"和"t3"。
(02) 主线程通过sleep(3000)休眠3秒。在主线程休眠3秒的过程中,我们假设"t1", "t2"和"t3"这3个线程都运行了。以"t1"为例,当它运行的时候,它会执行obj.wait()等待其它线程通过notify()或额nofityAll()来唤醒它;相同的道理,"t2"和"t3"也会等待其它线程通过nofity()或nofityAll()来唤醒它们。
(03) 主线程休眠3秒之后,接着运行。执行 obj.notifyAll() 唤醒obj上的等待线程,即唤醒"t1", "t2"和"t3"这3个线程。 紧接着,主线程的synchronized(obj)运行完毕之后,主线程释放“obj锁”。这样,"t1", "t2"和"t3"就可以获取“obj锁”而继续运行了!

5. 为什么notify(), wait()等函数定义在Object中,而不是Thread中

Object中的wait(), notify()等函数,和synchronized一样,会对“对象的同步锁”进行操作。

wait()会使“当前线程”等待,因为线程进入等待状态,所以线程应该释放它锁持有的“同步锁”,否则其它线程获取不到该“同步锁”而无法运行!
OK,线程调用wait()之后,会释放它锁持有的“同步锁”;而且,根据前面的介绍,我们知道:等待线程可以被notify()或notifyAll()唤醒。现在,请思考一个问题:notify()是依据什么唤醒等待线程的?或者说,wait()等待线程和notify()之间是通过什么关联起来的?答案是:依据“对象的同步锁”

负责唤醒等待线程的那个线程(我们称为“唤醒线程”),它只有在获取“该对象的同步锁”(这里的同步锁必须和等待线程的同步锁是同一个),并且调用notify()或notifyAll()方法之后,才能唤醒等待线程。虽然,等待线程被唤醒;但是,它不能立刻执行,因为唤醒线程还持有“该对象的同步锁”。必须等到唤醒线程释放了“对象的同步锁”之后,等待线程才能获取到“对象的同步锁”进而继续运行。

总之,notify(), wait()依赖于“同步锁”,而“同步锁”是对象锁持有,并且每个对象有且仅有一个!这就是为什么notify(), wait()等函数定义在Object类,而不是Thread类中的原因。

 

概要

本章,会对Thread中的线程让步方法yield()进行介绍。涉及到的内容包括:
1. yield()介绍
2. yield()示例
3. yield() 与 wait()的比较

转载请注明出处http://www.cnblogs.com/skywang12345/p/3479243.html

1. yield()介绍

yield()的作用是让步。它能让当前线程由“运行状态”进入到“就绪状态”,从而让其它具有相同优先级的等待线程获取执行权;但是,并不能保证在当前线程调用yield()之后,其它具有相同优先级的线程就一定能获得执行权;也有可能是当前线程又进入到“运行状态”继续运行!

2. yield()示例

下面,通过示例查看它的用法。

复制代码
 1 // YieldTest.java的源码
 2 class ThreadA extends Thread{
 3     public ThreadA(String name){ 
 4         super(name); 
 5     } 
 6     public synchronized void run(){ 
 7         for(int i=0; i <10; i++){ 
 8             System.out.printf("%s [%d]:%d\n", this.getName(), this.getPriority(), i); 
 9             // i整除4时,调用yield
10             if (i%4 == 0)
11                 Thread.yield();
12         } 
13     } 
14 } 
15 
16 public class YieldTest{ 
17     public static void main(String[] args){ 
18         ThreadA t1 = new ThreadA("t1"); 
19         ThreadA t2 = new ThreadA("t2"); 
20         t1.start(); 
21         t2.start();
22     } 
23 } 
复制代码

(某一次的)运行结果:

复制代码
t1 [5]:0
t2 [5]:0
t1 [5]:1
t1 [5]:2
t1 [5]:3
t1 [5]:4
t1 [5]:5
t1 [5]:6
t1 [5]:7
t1 [5]:8
t1 [5]:9
t2 [5]:1
t2 [5]:2
t2 [5]:3
t2 [5]:4
t2 [5]:5
t2 [5]:6
t2 [5]:7
t2 [5]:8
t2 [5]:9
复制代码

结果说明
“线程t1”在能被4整数的时候,并没有切换到“线程t2”。这表明,yield()虽然可以让线程由“运行状态”进入到“就绪状态”;但是,它不一定会让其它线程获取CPU执行权(即,其它线程进入到“运行状态”),即使这个“其它线程”与当前调用yield()的线程具有相同的优先级。

 

3. yield() 与 wait()的比较

我们知道,wait()的作用是让当前线程由“运行状态”进入“等待(阻塞)状态”的同时,也会释放同步锁。而yield()的作用是让步,它也会让当前线程离开“运行状态”。它们的区别是:
(01) wait()是让线程由“运行状态”进入到“等待(阻塞)状态”,而不yield()是让线程由“运行状态”进入到“就绪状态”。
(02) wait()是会线程释放它所持有对象的同步锁,而yield()方法不会释放锁。

下面通过示例演示yield()是不会释放锁的。

复制代码
 1 // YieldLockTest.java 的源码
 2 public class YieldLockTest{ 
 3 
 4     private static Object obj = new Object();
 5 
 6     public static void main(String[] args){ 
 7         ThreadA t1 = new ThreadA("t1"); 
 8         ThreadA t2 = new ThreadA("t2"); 
 9         t1.start(); 
10         t2.start();
11     } 
12 
13     static class ThreadA extends Thread{
14         public ThreadA(String name){ 
15             super(name); 
16         } 
17         public void run(){ 
18             // 获取obj对象的同步锁
19             synchronized (obj) {
20                 for(int i=0; i <10; i++){ 
21                     System.out.printf("%s [%d]:%d\n", this.getName(), this.getPriority(), i); 
22                     // i整除4时,调用yield
23                     if (i%4 == 0)
24                         Thread.yield();
25                 }
26             }
27         } 
28     } 
29 } 
复制代码

(某一次)运行结果

复制代码
t1 [5]:0
t1 [5]:1
t1 [5]:2
t1 [5]:3
t1 [5]:4
t1 [5]:5
t1 [5]:6
t1 [5]:7
t1 [5]:8
t1 [5]:9
t2 [5]:0
t2 [5]:1
t2 [5]:2
t2 [5]:3
t2 [5]:4
t2 [5]:5
t2 [5]:6
t2 [5]:7
t2 [5]:8
t2 [5]:9
复制代码

结果说明
主线程main中启动了两个线程t1和t2。t1和t2在run()会引用同一个对象的同步锁,即synchronized(obj)。在t1运行过程中,虽然它会调用Thread.yield();但是,t2是不会获取cpu执行权的。因为,t1并没有释放“obj所持有的同步锁”!

 

概要

本章,会对Thread中sleep()方法进行介绍。涉及到的内容包括:
1. sleep()介绍
2. sleep()示例
3. sleep() 与 wait()的比较

转载请注明出处:http://www.cnblogs.com/skywang12345/p/3479256.html

1. sleep()介绍

sleep() 定义在Thread.java中。
sleep() 的作用是让当前线程休眠,即当前线程会从“运行状态”进入到“休眠(阻塞)状态”。sleep()会指定休眠时间,线程休眠的时间会大于/等于该休眠时间;在线程重新被唤醒时,它会由“阻塞状态”变成“就绪状态”,从而等待cpu的调度执行。

2. sleep()示例

下面通过一个简单示例演示sleep()的用法。

复制代码
 1 // SleepTest.java的源码
 2 class ThreadA extends Thread{
 3     public ThreadA(String name){ 
 4         super(name); 
 5     } 
 6     public synchronized void run() { 
 7         try {
 8             for(int i=0; i <10; i++){ 
 9                 System.out.printf("%s: %d\n", this.getName(), i); 
10                 // i能被4整除时,休眠100毫秒
11                 if (i%4 == 0)
12                     Thread.sleep(100);
13             } 
14         } catch (InterruptedException e) {
15             e.printStackTrace();
16         }
17     } 
18 } 
19 
20 public class SleepTest{ 
21     public static void main(String[] args){ 
22         ThreadA t1 = new ThreadA("t1"); 
23         t1.start(); 
24     } 
25 } 
复制代码

运行结果

复制代码
t1: 0
t1: 1
t1: 2
t1: 3
t1: 4
t1: 5
t1: 6
t1: 7
t1: 8
t1: 9
复制代码

结果说明
程序比较简单,在主线程main中启动线程t1。t1启动之后,当t1中的计算i能被4整除时,t1会通过Thread.sleep(100)休眠100毫秒。

3. sleep() 与 wait()的比较

我们知道,wait()的作用是让当前线程由“运行状态”进入“等待(阻塞)状态”的同时,也会释放同步锁。而sleep()的作用是也是让当前线程由“运行状态”进入到“休眠(阻塞)状态”。
但是,wait()会释放对象的同步锁,而sleep()则不会释放锁。
下面通过示例演示sleep()是不会释放锁的。

复制代码
 1 // SleepLockTest.java的源码
 2 public class SleepLockTest{ 
 3 
 4     private static Object obj = new Object();
 5 
 6     public static void main(String[] args){ 
 7         ThreadA t1 = new ThreadA("t1"); 
 8         ThreadA t2 = new ThreadA("t2"); 
 9         t1.start(); 
10         t2.start();
11     } 
12 
13     static class ThreadA extends Thread{
14         public ThreadA(String name){ 
15             super(name); 
16         } 
17         public void run(){ 
18             // 获取obj对象的同步锁
19             synchronized (obj) {
20                 try {
21                     for(int i=0; i <10; i++){ 
22                         System.out.printf("%s: %d\n", this.getName(), i); 
23                         // i能被4整除时,休眠100毫秒
24                         if (i%4 == 0)
25                             Thread.sleep(100);
26                     }
27                 } catch (InterruptedException e) {
28                     e.printStackTrace();
29                 }
30             }
31         } 
32     } 
33 } 
复制代码

运行结果

复制代码
t1: 0
t1: 1
t1: 2
t1: 3
t1: 4
t1: 5
t1: 6
t1: 7
t1: 8
t1: 9
t2: 0
t2: 1
t2: 2
t2: 3
t2: 4
t2: 5
t2: 6
t2: 7
t2: 8
t2: 9
复制代码

结果说明
主线程main中启动了两个线程t1和t2。t1和t2在run()会引用同一个对象的同步锁,即synchronized(obj)。在t1运行过程中,虽然它会调用Thread.sleep(100);但是,t2是不会获取cpu执行权的。因为,t1并没有释放“obj所持有的同步锁”!
注意,若我们注释掉synchronized (obj)后再次执行该程序,t1和t2是可以相互切换的。下面是注释调synchronized(obj) 之后的源码:

复制代码
 1 // SleepLockTest.java的源码(注释掉synchronized(obj))
 2 public class SleepLockTest{ 
 3 
 4     private static Object obj = new Object();
 5 
 6     public static void main(String[] args){ 
 7         ThreadA t1 = new ThreadA("t1"); 
 8         ThreadA t2 = new ThreadA("t2"); 
 9         t1.start(); 
10         t2.start();
11     } 
12 
13     static class ThreadA extends Thread{
14         public ThreadA(String name){ 
15             super(name); 
16         } 
17         public void run(){ 
18             // 获取obj对象的同步锁
19 //            synchronized (obj) {
20                 try {
21                     for(int i=0; i <10; i++){ 
22                         System.out.printf("%s: %d\n", this.getName(), i); 
23                         // i能被4整除时,休眠100毫秒
24                         if (i%4 == 0)
25                             Thread.sleep(100);
26                     }
27                 } catch (InterruptedException e) {
28                     e.printStackTrace();
29                 }
30 //            }
31         } 
32     } 
33 } 
复制代码

概要

本章,会对Thread中join()方法进行介绍。涉及到的内容包括:
1. join()介绍
2. join()源码分析(基于JDK1.7.0_40)
3. join()示例

转载请注明出处:http://www.cnblogs.com/skywang12345/p/3479275.html

1. join()介绍

join() 定义在Thread.java中。
join() 的作用:让“主线程”等待“子线程”结束之后才能继续运行。这句话可能有点晦涩,我们还是通过例子去理解:

复制代码
// 主线程
public class Father extends Thread {
    public void run() {
        Son s = new Son();
        s.start();
        s.join();
        ...
    }
}
// 子线程
public class Son extends Thread {
    public void run() {
        ...
    }
}
复制代码

说明
上面的有两个类Father(主线程类)和Son(子线程类)。因为Son是在Father中创建并启动的,所以,Father是主线程类,Son是子线程类。
在Father主线程中,通过new Son()新建“子线程s”。接着通过s.start()启动“子线程s”,并且调用s.join()。在调用s.join()之后,Father主线程会一直等待,直到“子线程s”运行完毕;在“子线程s”运行完毕之后,Father主线程才能接着运行。 这也就是我们所说的“join()的作用,是让主线程会等待子线程结束之后才能继续运行”!

2. join()源码分析(基于JDK1.7.0_40)

复制代码
public final void join() throws InterruptedException {
    join(0);
}

public final synchronized void join(long millis)
throws InterruptedException {
    long base = System.currentTimeMillis();
    long now = 0;

    if (millis < 0) {
        throw new IllegalArgumentException("timeout value is negative");
    }

    if (millis == 0) {
        while (isAlive()) {
            wait(0);
        }
    } else {
        while (isAlive()) {
            long delay = millis - now;
            if (delay <= 0) {
                break;
            }
            wait(delay);
            now = System.currentTimeMillis() - base;
        }
    }
}
复制代码

说明
从代码中,我们可以发现。当millis==0时,会进入while(isAlive())循环;即只要子线程是活的,主线程就不停的等待。
我们根据上面解释join()作用时的代码来理解join()的用法!
问题
虽然s.join()被调用的地方是发生在“Father主线程”中,但是s.join()是通过“子线程s”去调用的join()。那么,join()方法中的isAlive()应该是判断“子线程s”是不是Alive状态;对应的wait(0)也应该是“让子线程s”等待才对。但如果是这样的话,s.join()的作用怎么可能是“让主线程等待,直到子线程s完成为止”呢,应该是让"子线程等待才对(因为调用子线程对象s的wait方法嘛)"?
答案wait()的作用是让“当前线程”等待,而这里的“当前线程”是指当前在CPU上运行的线程。所以,虽然是调用子线程的wait()方法,但是它是通过“主线程”去调用的;所以,休眠的是主线程,而不是“子线程”!

 

3. join()示例

在理解join()的作用之后,接下来通过示例查看join()的用法。

复制代码
// JoinTest.java的源码
public class JoinTest{ 

    public static void main(String[] args){ 
        try {
            ThreadA t1 = new ThreadA("t1"); // 新建“线程t1”

            t1.start();                     // 启动“线程t1”
            t1.join();                        // 将“线程t1”加入到“主线程main”中,并且“主线程main()会等待它的完成”
            System.out.printf("%s finish\n", Thread.currentThread().getName()); 
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } 

    static class ThreadA extends Thread{

        public ThreadA(String name){ 
            super(name); 
        } 
        public void run(){ 
            System.out.printf("%s start\n", this.getName()); 

            // 延时操作
            for(int i=0; i <1000000; i++)
               ;

            System.out.printf("%s finish\n", this.getName()); 
        } 
    } 
}
复制代码

运行结果

t1 start
t1 finish
main finish

结果说明
运行流程如图 
(01) 在“主线程main”中通过 new ThreadA("t1") 新建“线程t1”。 接着,通过 t1.start() 启动“线程t1”,并执行t1.join()。
(02) 执行t1.join()之后,“主线程main”会进入“阻塞状态”等待t1运行结束。“子线程t1”结束之后,会唤醒“主线程main”,“主线程”重新获取cpu执行权,继续运行。

概要

本章,会对线程的interrupt()中断和终止方式进行介绍。涉及到的内容包括:
1. interrupt()说明
2. 终止线程的方式
  2.1 终止处于“阻塞状态”的线程
  2.2 终止处于“运行状态”的线程
3. 终止线程的示例
4. interrupted() 和 isInterrupted()的区别

转载请注明出处:http://www.cnblogs.com/skywang12345/p/3479949.html

1. interrupt()说明

在介绍终止线程的方式之前,有必要先对interrupt()进行了解。
关于interrupt(),java的djk文档描述如下:http://docs.oracle.com/javase/7/docs/api/

复制代码
Interrupts this thread.
Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.

If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.

If none of the previous conditions hold then this thread's interrupt status will be set.

Interrupting a thread that is not alive need not have any effect.
复制代码

大致意思是:

复制代码
interrupt()的作用是中断本线程。
本线程中断自己是被允许的;其它线程调用本线程的interrupt()方法时,会通过checkAccess()检查权限。这有可能抛出SecurityException异常。
如果本线程是处于阻塞状态:调用线程的wait(), wait(long)或wait(long, int)会让它进入等待(阻塞)状态,或者调用线程的join(), join(long), join(long, int), sleep(long), sleep(long, int)也会让它进入阻塞状态。若线程在阻塞状态时,调用了它的interrupt()方法,那么它的“中断状态”会被清除并且会收到一个InterruptedException异常。例如,线程通过wait()进入阻塞状态,此时通过interrupt()中断该线程;调用interrupt()会立即将线程的中断标记设为“true”,但是由于线程处于阻塞状态,所以该“中断标记”会立即被清除为“false”,同时,会产生一个InterruptedException的异常。
如果线程被阻塞在一个Selector选择器中,那么通过interrupt()中断它时;线程的中断标记会被设置为true,并且它会立即从选择操作中返回。
如果不属于前面所说的情况,那么通过interrupt()中断线程时,它的中断标记会被设置为“true”。
中断一个“已终止的线程”不会产生任何操作。
复制代码

2. 终止线程的方式

Thread中的stop()和suspend()方法,由于固有的不安全性,已经建议不再使用!
下面,我先分别讨论线程在“阻塞状态”和“运行状态”的终止方式,然后再总结出一个通用的方式。

2.1 终止处于“阻塞状态”的线程

通常,我们通过“中断”方式终止处于“阻塞状态”的线程。
当线程由于被调用了sleep(), wait(), join()等方法而进入阻塞状态;若此时调用线程的interrupt()将线程的中断标记设为true。由于处于阻塞状态,中断标记会被清除,同时产生一个InterruptedException异常。将InterruptedException放在适当的为止就能终止线程,形式如下:

复制代码
@Override
public void run() {
    try {
        while (true) {
            // 执行任务...
        }
    } catch (InterruptedException ie) {  
        // 由于产生InterruptedException异常,退出while(true)循环,线程终止!
    }
}
复制代码

说明:在while(true)中不断的执行任务,当线程处于阻塞状态时,调用线程的interrupt()产生InterruptedException中断。中断的捕获在while(true)之外,这样就退出了while(true)循环!
注意:对InterruptedException的捕获务一般放在while(true)循环体的外面,这样,在产生异常时就退出了while(true)循环。否则,InterruptedException在while(true)循环体之内,就需要额外的添加退出处理。形式如下:

复制代码
@Override
public void run() {
    while (true) {
        try {
            // 执行任务...
        } catch (InterruptedException ie) {  
            // InterruptedException在while(true)循环体内。
            // 当线程产生了InterruptedException异常时,while(true)仍能继续运行!需要手动退出
            break;
        }
    }
}
复制代码

说明:上面的InterruptedException异常的捕获在whle(true)之内。当产生InterruptedException异常时,被catch处理之外,仍然在while(true)循环体内;要退出while(true)循环体,需要额外的执行退出while(true)的操作。

2.2 终止处于“运行状态”的线程

通常,我们通过“标记”方式终止处于“运行状态”的线程。其中,包括“中断标记”和“额外添加标记”。
(01) 通过“中断标记”终止线程。
形式如下:

@Override
public void run() {
    while (!isInterrupted()) {
        // 执行任务...
    }
}

说明:isInterrupted()是判断线程的中断标记是不是为true。当线程处于运行状态,并且我们需要终止它时;可以调用线程的interrupt()方法,使用线程的中断标记为true,即isInterrupted()会返回true。此时,就会退出while循环。
注意:interrupt()并不会终止处于“运行状态”的线程!它会将线程的中断标记设为true。

(02) 通过“额外添加标记”。
形式如下:

复制代码
private volatile boolean flag= true;
protected void stopTask() {
    flag = false;
}

@Override
public void run() {
    while (flag) {
        // 执行任务...
    }
}
复制代码

说明:线程中有一个flag标记,它的默认值是true;并且我们提供stopTask()来设置flag标记。当我们需要终止该线程时,调用该线程的stopTask()方法就可以让线程退出while循环。
注意:将flag定义为volatile类型,是为了保证flag的可见性。即其它线程通过stopTask()修改了flag之后,本线程能看到修改后的flag的值。

综合线程处于“阻塞状态”和“运行状态”的终止方式,比较通用的终止线程的形式如下:

复制代码
@Override
public void run() {
    try {
        // 1. isInterrupted()保证,只要中断标记为true就终止线程。
        while (!isInterrupted()) {
            // 执行任务...
        }
    } catch (InterruptedException ie) {  
        // 2. InterruptedException异常保证,当InterruptedException异常产生时,线程被终止。
    }
}
复制代码

3. 终止线程的示例

interrupt()常常被用来终止“阻塞状态”线程。参考下面示例:

复制代码
 1 // Demo1.java的源码
 2 class MyThread extends Thread {
 3     
 4     public MyThread(String name) {
 5         super(name);
 6     }
 7 
 8     @Override
 9     public void run() {
10         try {  
11             int i=0;
12             while (!isInterrupted()) {
13                 Thread.sleep(100); // 休眠100ms
14                 i++;
15                 System.out.println(Thread.currentThread().getName()+" ("+this.getState()+") loop " + i);  
16             }
17         } catch (InterruptedException e) {  
18             System.out.println(Thread.currentThread().getName() +" ("+this.getState()+") catch InterruptedException.");  
19         }
20     }
21 }
22 
23 public class Demo1 {
24 
25     public static void main(String[] args) {  
26         try {  
27             Thread t1 = new MyThread("t1");  // 新建“线程t1”
28             System.out.println(t1.getName() +" ("+t1.getState()+") is new.");  
29 
30             t1.start();                      // 启动“线程t1”
31             System.out.println(t1.getName() +" ("+t1.getState()+") is started.");  
32 
33             // 主线程休眠300ms,然后主线程给t1发“中断”指令。
34             Thread.sleep(300);
35             t1.interrupt();
36             System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted.");
37 
38             // 主线程休眠300ms,然后查看t1的状态。
39             Thread.sleep(300);
40             System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted now.");
41         } catch (InterruptedException e) {  
42             e.printStackTrace();
43         }
44     } 
45 }
复制代码

运行结果

复制代码
t1 (NEW) is new.
t1 (RUNNABLE) is started.
t1 (RUNNABLE) loop 1
t1 (RUNNABLE) loop 2
t1 (TIMED_WAITING) is interrupted.
t1 (RUNNABLE) catch InterruptedException.
t1 (TERMINATED) is interrupted now.
复制代码

结果说明
(01) 主线程main中通过new MyThread("t1")创建线程t1,之后通过t1.start()启动线程t1。
(02) t1启动之后,会不断的检查它的中断标记,如果中断标记为“false”;则休眠100ms。
(03) t1休眠之后,会切换到主线程main;主线程再次运行时,会执行t1.interrupt()中断线程t1。t1收到中断指令之后,会将t1的中断标记设置“false”,而且会抛出InterruptedException异常。在t1的run()方法中,是在循环体while之外捕获的异常;因此循环被终止。

我们对上面的结果进行小小的修改,将run()方法中捕获InterruptedException异常的代码块移到while循环体内。

复制代码
 1 // Demo2.java的源码
 2 class MyThread extends Thread {
 3     
 4     public MyThread(String name) {
 5         super(name);
 6     }
 7 
 8     @Override
 9     public void run() {
10         int i=0;
11         while (!isInterrupted()) {
12             try {
13                 Thread.sleep(100); // 休眠100ms
14             } catch (InterruptedException ie) {  
15                 System.out.println(Thread.currentThread().getName() +" ("+this.getState()+") catch InterruptedException.");  
16             }
17             i++;
18             System.out.println(Thread.currentThread().getName()+" ("+this.getState()+") loop " + i);  
19         }
20     }
21 }
22 
23 public class Demo2 {
24 
25     public static void main(String[] args) {  
26         try {  
27             Thread t1 = new MyThread("t1");  // 新建“线程t1”
28             System.out.println(t1.getName() +" ("+t1.getState()+") is new.");  
29 
30             t1.start();                      // 启动“线程t1”
31             System.out.println(t1.getName() +" ("+t1.getState()+") is started.");  
32 
33             // 主线程休眠300ms,然后主线程给t1发“中断”指令。
34             Thread.sleep(300);
35             t1.interrupt();
36             System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted.");
37 
38             // 主线程休眠300ms,然后查看t1的状态。
39             Thread.sleep(300);
40             System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted now.");
41         } catch (InterruptedException e) {  
42             e.printStackTrace();
43         }
44     } 
45 }
复制代码

运行结果

复制代码
t1 (NEW) is new.
t1 (RUNNABLE) is started.
t1 (RUNNABLE) loop 1
t1 (RUNNABLE) loop 2
t1 (TIMED_WAITING) is interrupted.
t1 (RUNNABLE) catch InterruptedException.
t1 (RUNNABLE) loop 3
t1 (RUNNABLE) loop 4
t1 (RUNNABLE) loop 5
t1 (TIMED_WAITING) is interrupted now.
t1 (RUNNABLE) loop 6
t1 (RUNNABLE) loop 7
t1 (RUNNABLE) loop 8
t1 (RUNNABLE) loop 9
...
复制代码

结果说明
程序进入了死循环!
为什么会这样呢?这是因为,t1在“等待(阻塞)状态”时,被interrupt()中断;此时,会清除中断标记[即isInterrupted()会返回false],而且会抛出InterruptedException异常[该异常在while循环体内被捕获]。因此,t1理所当然的会进入死循环了。
解决该问题,需要我们在捕获异常时,额外的进行退出while循环的处理。例如,在MyThread的catch(InterruptedException)中添加break 或 return就能解决该问题。

下面是通过“额外添加标记”的方式终止“状态状态”的线程的示例:

复制代码
 1 // Demo3.java的源码
 2 class MyThread extends Thread {
 3 
 4     private volatile boolean flag= true;
 5     public void stopTask() {
 6         flag = false;
 7     }
 8     
 9     public MyThread(String name) {
10         super(name);
11     }
12 
13     @Override
14     public void run() {
15         synchronized(this) {
16             try {
17                 int i=0;
18                 while (flag) {
19                     Thread.sleep(100); // 休眠100ms
20                     i++;
21                     System.out.println(Thread.currentThread().getName()+" ("+this.getState()+") loop " + i);  
22                 }
23             } catch (InterruptedException ie) {  
24                 System.out.println(Thread.currentThread().getName() +" ("+this.getState()+") catch InterruptedException.");  
25             }
26         }  
27     }
28 }
29 
30 public class Demo3 {
31 
32     public static void main(String[] args) {  
33         try {  
34             MyThread t1 = new MyThread("t1");  // 新建“线程t1”
35             System.out.println(t1.getName() +" ("+t1.getState()+") is new.");  
36 
37             t1.start();                      // 启动“线程t1”
38             System.out.println(t1.getName() +" ("+t1.getState()+") is started.");  
39 
40             // 主线程休眠300ms,然后主线程给t1发“中断”指令。
41             Thread.sleep(300);
42             t1.stopTask();
43             System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted.");
44 
45             // 主线程休眠300ms,然后查看t1的状态。
46             Thread.sleep(300);
47             System.out.println(t1.getName() +" ("+t1.getState()+") is interrupted now.");
48         } catch (InterruptedException e) {  
49             e.printStackTrace();
50         }
51     } 
52 }
复制代码

运行结果

复制代码
t1 (NEW) is new.
t1 (RUNNABLE) is started.
t1 (RUNNABLE) loop 1
t1 (RUNNABLE) loop 2
t1 (TIMED_WAITING) is interrupted.
t1 (RUNNABLE) loop 3
t1 (TERMINATED) is interrupted now.
复制代码

4. interrupted() 和 isInterrupted()的区别

最后谈谈 interrupted() 和 isInterrupted()。
interrupted() 和 isInterrupted()都能够用于检测对象的“中断标记”。
区别是,interrupted()除了返回中断标记之外,它还会清除中断标记(即将中断标记设为false);而isInterrupted()仅仅返回中断标记。

概要

本章,会对“生产/消费者问题”进行讨论。涉及到的内容包括:
1. 生产/消费者模型
2. 生产/消费者实现

转载请注明出处:http://www.cnblogs.com/skywang12345/p/3480016.html

1. 生产/消费者模型

生产/消费者问题是个非常典型的多线程问题,涉及到的对象包括“生产者”、“消费者”、“仓库”和“产品”。他们之间的关系如下:
(01) 生产者仅仅在仓储未满时候生产,仓满则停止生产。
(02) 消费者仅仅在仓储有产品时候才能消费,仓空则等待。
(03) 当消费者发现仓储没产品可消费时候会通知生产者生产。
(04) 生产者在生产出可消费产品时候,应该通知等待的消费者去消费。

2. 生产/消费者实现

下面通过wait()/notify()方式实现该模型(后面在学习了线程池相关内容之后,再通过其它方式实现生产/消费者模型)。源码如下:

复制代码
  1 // Demo1.java
  2 // 仓库
  3 class Depot {
  4     private int capacity;    // 仓库的容量
  5     private int size;        // 仓库的实际数量
  6 
  7     public Depot(int capacity) {
  8         this.capacity = capacity;
  9         this.size = 0;
 10     }
 11 
 12     public synchronized void produce(int val) {
 13         try {
 14              // left 表示“想要生产的数量”(有可能生产量太多,需多此生产)
 15             int left = val;
 16             while (left > 0) {
 17                 // 库存已满时,等待“消费者”消费产品。
 18                 while (size >= capacity)
 19                     wait();
 20                 // 获取“实际生产的数量”(即库存中新增的数量)
 21                 // 如果“库存”+“想要生产的数量”>“总的容量”,则“实际增量”=“总的容量”-“当前容量”。(此时填满仓库)
 22                 // 否则“实际增量”=“想要生产的数量”
 23                 int inc = (size+left)>capacity ? (capacity-size) : left;
 24                 size += inc;
 25                 left -= inc;
 26                 System.out.printf("%s produce(%3d) --> left=%3d, inc=%3d, size=%3d\n", 
 27                         Thread.currentThread().getName(), val, left, inc, size);
 28                 // 通知“消费者”可以消费了。
 29                 notifyAll();
 30             }
 31         } catch (InterruptedException e) {
 32         }
 33     } 
 34 
 35     public synchronized void consume(int val) {
 36         try {
 37             // left 表示“客户要消费数量”(有可能消费量太大,库存不够,需多此消费)
 38             int left = val;
 39             while (left > 0) {
 40                 // 库存为0时,等待“生产者”生产产品。
 41                 while (size <= 0)
 42                     wait();
 43                 // 获取“实际消费的数量”(即库存中实际减少的数量)
 44                 // 如果“库存”<“客户要消费的数量”,则“实际消费量”=“库存”;
 45                 // 否则,“实际消费量”=“客户要消费的数量”。
 46                 int dec = (size<left) ? size : left;
 47                 size -= dec;
 48                 left -= dec;
 49                 System.out.printf("%s consume(%3d) <-- left=%3d, dec=%3d, size=%3d\n", 
 50                         Thread.currentThread().getName(), val, left, dec, size);
 51                 notifyAll();
 52             }
 53         } catch (InterruptedException e) {
 54         }
 55     }
 56 
 57     public String toString() {
 58         return "capacity:"+capacity+", actual size:"+size;
 59     }
 60 } 
 61 
 62 // 生产者
 63 class Producer {
 64     private Depot depot;
 65     
 66     public Producer(Depot depot) {
 67         this.depot = depot;
 68     }
 69 
 70     // 消费产品:新建一个线程向仓库中生产产品。
 71     public void produce(final int val) {
 72         new Thread() {
 73             public void run() {
 74                 depot.produce(val);
 75             }
 76         }.start();
 77     }
 78 }
 79 
 80 // 消费者
 81 class Customer {
 82     private Depot depot;
 83     
 84     public Customer(Depot depot) {
 85         this.depot = depot;
 86     }
 87 
 88     // 消费产品:新建一个线程从仓库中消费产品。
 89     public void consume(final int val) {
 90         new Thread() {
 91             public void run() {
 92                 depot.consume(val);
 93             }
 94         }.start();
 95     }
 96 }
 97 
 98 public class Demo1 {  
 99     public static void main(String[] args) {  
100         Depot mDepot = new Depot(100);
101         Producer mPro = new Producer(mDepot);
102         Customer mCus = new Customer(mDepot);
103 
104         mPro.produce(60);
105         mPro.produce(120);
106         mCus.consume(90);
107         mCus.consume(150);
108         mPro.produce(110);
109     }
110 }
复制代码

说明
(01) Producer是“生产者”类,它与“仓库(depot)”关联。当调用“生产者”的produce()方法时,它会新建一个线程并向“仓库”中生产产品。
(02) Customer是“消费者”类,它与“仓库(depot)”关联。当调用“消费者”的consume()方法时,它会新建一个线程并消费“仓库”中的产品。
(03) Depot是“仓库”类,仓库中记录“仓库的容量(capacity)”以及“仓库中当前产品数目(size)”。
        “仓库”类的生产方法produce()和消费方法consume()方法都是synchronized方法,进入synchronized方法体,意味着这个线程获取到了该“仓库”对象的同步锁。这也就是说,同一时间,生产者和消费者线程只能有一个能运行。通过同步锁,实现了对“残酷”的互斥访问。
       对于生产方法produce()而言:当仓库满时,生产者线程等待,需要等待消费者消费产品之后,生产线程才能生产;生产者线程生产完产品之后,会通过notifyAll()唤醒同步锁上的所有线程,包括“消费者线程”,即我们所说的“通知消费者进行消费”。
      对于消费方法consume()而言:当仓库为空时,消费者线程等待,需要等待生产者生产产品之后,消费者线程才能消费;消费者线程消费完产品之后,会通过notifyAll()唤醒同步锁上的所有线程,包括“生产者线程”,即我们所说的“通知生产者进行生产”。

(某一次)运行结果

复制代码
Thread-0 produce( 60) --> left=  0, inc= 60, size= 60
Thread-4 produce(110) --> left= 70, inc= 40, size=100
Thread-2 consume( 90) <-- left=  0, dec= 90, size= 10
Thread-3 consume(150) <-- left=140, dec= 10, size=  0
Thread-1 produce(120) --> left= 20, inc=100, size=100
Thread-3 consume(150) <-- left= 40, dec=100, size=  0
Thread-4 produce(110) --> left=  0, inc= 70, size= 70
Thread-3 consume(150) <-- left=  0, dec= 40, size= 30
Thread-1 produce(120) --> left=  0, inc= 20, size= 50

猜你喜欢

转载自blog.csdn.net/fuweihua123/article/details/80859328