彻底明白Java的多线程-线程间的通信

来源:互联网 发布:淘宝助理不能一键适配 编辑:程序博客网 时间:2024/05/16 19:38

一. 实现多线程
1. 虚假的多线程
例1:
publicclassTestThread
{
inti=0, j=0;
publicvoidgo(intflag){
while(true){
try{
java/lang/Thread.java.html" target="_blank">
Thread
.sleep(100);
}
catch(java/lang/InterruptedException.java.html" target="_blank">
InterruptedException
e){
java/lang/System.java.html" target="_blank">
System
.out.println("Interrupted");
}
if(flag==0)
i++;
java/lang/System.java.html" target="_blank">
System
.out.println("i=" + i);
}
else{
j++;
java/lang/System.java.html" target="_blank">
System
.out.println("j=" + j);
}
}
}
publicstaticvoidmain(java/lang/String.java.html" target="_blank">
String
[] args){
newTestThread().go(0);
newTestThread().go(1);
}
}

上面程序的运行结果为:
i=1
i=2
i=3
。。。
结果将一直打印出I的值。我们的意图是当在while循环中调用sleep()时,另一个线程就将起动,打印出j的值,但结果却并不是这样。关于sleep()为什么不会出现我们预想的结果,在下面将讲到。
2. 实现多线程
通过继承class Thread或实现Runnable接口,我们可以实现多线程
2.1 通过继承class Thread实现多线程
class Thread中有两个最重要的函数run()和start()。
1) run()函数必须进行覆写,把要在多个线程中并行处理的代码放到这个函数中。
2)虽然run()函数实现了多个线程的并行处理,但我们不能直接调用run()函数,而是通过调用start()函数来调用run()函数。在调用start()的时候,start()函数会首先进行与多线程相关的初始化(这也是为什么不能直接调用run()函数的原因),然后再调用run()函数。
例2:

publicclassTestThread extendsjava/lang/Thread.java.html" target="_blank">
Thread
{
privatestaticintthreadCount = 0;
privateintthreadNum = ++threadCount;
privateinti = 5;
publicvoidrun(){
while(true){
try{
java/lang/Thread.java.html" target="_blank">
Thread
.sleep(100); 
}
catch(java/lang/InterruptedException.java.html" target="_blank">
InterruptedException
e){
java/lang/System.java.html" target="_blank">
System
.out.println("Interrupted");
}
java/lang/System.java.html" target="_blank">
System
.out.println("Thread " + threadNum + " = " + i);
if(--i==0) return;
}
}
>publicstaticvoidmain(java/lang/String.java.html" target="_blank">
String
[] args){
for(inti=0; i<5; i++)
newTestThread().start();
}
}

运行结果为:
Thread 1 = 5
Thread 2 = 5
Thread 3 = 5
Thread 4 = 5
Thread 5 = 5
Thread 1 = 4
Thread 2 = 4
Thread 3 = 4
Thread 4 = 4
Thread 1 = 3
Thread 2 = 3
Thread 5 = 4
Thread 3 = 3
Thread 4 = 3
Thread 1 = 2
Thread 2 = 2
Thread 5 = 3
Thread 3 = 2
Thread 4 = 2
Thread 1 = 1
Thread 2 = 1
Thread 5 = 2
Thread 3 = 1
Thread 4 = 1
Thread 5 = 1
从结果可见,例2能实现多线程的并行处理。
**:在上面的例子中,我们只用new产生Thread对象,并没有用reference来记录所产生的Thread对象。根据垃圾回收机制,当一个对象没有被reference引用时,它将被回收。但是垃圾回收机制对Thread对象“不成立”。因为每一个Thread都会进行注册动作,所以即使我们在产生Thread对象时没有指定一个reference指向这个对象,实际上也会在某个地方有个指向该对象的reference,所以垃圾回收器无法回收它们。
3) 通过Thread的子类产生的线程对象是不同对象的线程

classTestSynchronized extendsjava/lang/Thread.java.html" target="_blank">
Thread
{
publicTestSynchronized(java/lang/String.java.html" target="_blank">
String
name){
super(name);
}
publicsynchronizedstaticvoidprt(){
for(inti=10; i<20; i++){
java/lang/System.java.html" target="_blank">
System
.out.println(java/lang/Thread.java.html" target="_blank">
Thread
.currentThread().getName() + " : " + i);
try{
java/lang/Thread.java.html" target="_blank">
Thread
.sleep(100);
}
catch(java/lang/InterruptedException.java.html" target="_blank">
InterruptedException
e){
java/lang/System.java.html" target="_blank">
System
.out.println("Interrupted");
}
}
}
publicsynchronizedvoidrun(){
for(inti=0; i<3; i++){
java/lang/System.java.html" target="_blank">
System
.out.println(java/lang/Thread.java.html" target="_blank">
Thread
.currentThread().getName() + " : " + i);
try{
java/lang/Thread.java.html" target="_blank">
Thread
.sleep(100);
}
catch(java/lang/InterruptedException.java.html" target="_blank">
InterruptedException
e){
java/lang/System.java.html" target="_blank">
System
.out.println("Interrupted");
}
}
}
}
publicclassTestThread{
publicstaticvoidmain(java/lang/String.java.html" target="_blank">
String
[] args){
TestSynchronized t1 = newTestSynchronized("t1");
TestSynchronized t2 = newTestSynchronized("t2");
t1.start();
t1.start(); //(1)
//t2.start(); (2)
}
}

运行结果为:
t1 : 0
t1 : 1
t1 : 2
t1 : 0
t1 : 1
t1 : 2
由于是同一个对象启动的不同线程,所以run()函数实现了synchronized。如果去掉(2)的注释,把代码(1)注释掉,结果将变为:
t1 : 0
t2 : 0
t1 : 1
t2 : 1
t1 : 2
t2 : 2
由于t1和t2是两个对象,所以它们所启动的线程可同时访问run()函数。
2.2 通过实现Runnable接口实现多线程
如果有一个类,它已继承了某个类,又想实现多线程,那就可以通过实现Runnable接口来实现。
1) Runnable接口只有一个run()函数。
2)把一个实现了Runnable接口的对象作为参数产生一个Thread对象,再调用Thread对象的start()函数就可执行并行操作。如果在产生一个Thread对象时以一个Runnable接口的实现类的对象作为参数,那么在调用start()函数时,start()会调用Runnable接口的实现类中的run()函数。
例3.1:

publicclassTestThread implementsjava/lang/Runnable.java.html" target="_blank">
Runnable
{
privatestaticintthreadCount = 0;
privateintthreadNum = ++threadCount;
privateinti = 5;
publicvoidrun(){
while(true){
try{
java/lang/Thread.java.html" target="_blank">
Thread
.sleep(100);
}
catch(java/lang/InterruptedException.java.html" target="_blank">
InterruptedException
e){
java/lang/System.java.html" target="_blank">
System
.out.println("Interrupted");
}
java/lang/System.java.html" target="_blank">
System
.out.println("Thread " + threadNum + " = " + i);
if(--i==0) return;
}
}
publicstaticvoidmain(java/lang/String.java.html" target="_blank">
String
[] args){
for(inti=0; i<5; i++)
newjava/lang/Thread.java.html" target="_blank">
Thread
(newTestThread()).start(); //(1)
}
}

运行结果为:
Thread 1 = 5
Thread 2 = 5
Thread 3 = 5
Thread 4 = 5
Thread 5 = 5
Thread 1 = 4
Thread 2 = 4
Thread 3 = 4
Thread 4 = 4
Thread 4 = 3
Thread 5 = 4
Thread 1 = 3
Thread 2 = 3
Thread 3 = 3
Thread 4 = 2
Thread 5 = 3
Thread 1 = 2
Thread 2 = 2
Thread 3 = 2
Thread 4 = 1
Thread 5 = 2
Thread 1 = 1
Thread 2 = 1
Thread 3 = 1
Thread 5 = 1
例3是对例2的修改,它通过实现Runnable接口来实现并行处理。代码(1)处可见,要调用TestThread中的并行操作部分,要把一个TestThread对象作为参数来产生Thread对象,再调用Thread对象的start()函数。
3) 同一个实现了Runnable接口的对象作为参数产生的所有Thread对象是同一对象下的线程。
例3.2:

packagemypackage1;
publicclassTestThread implementsjava/lang/Runnable.java.html" target="_blank">
Runnable
{
publicsynchronizedvoidrun(){
for(inti=0; i<5; i++){
java/lang/System.java.html" target="_blank">
System
.out.println(java/lang/Thread.java.html" target="_blank">
Thread
.currentThread().getName() + " : " + i);
try{
java/lang/Thread.java.html" target="_blank">
Thread
.sleep(100);
}
catch(java/lang/InterruptedException.java.html" target="_blank">
InterruptedException
e){
java/lang/System.java.html" target="_blank">
System
.out.println("Interrupted");
}
}
}
publicstaticvoidmain(java/lang/String.java.html" target="_blank">
String
[] args){
TestThread testThread = newTestThread();
for(inti=0; i<5; i++)
//new Thread(testThread, "t" + i).start(); (1)
newjava/lang/Thread.java.html" target="_blank">
Thread
(newTestThread(), "t" + i).start(); (2)
}
}

运行结果为:
t0 : 0
t1 : 0
t2 : 0
t3 : 0
t4 : 0
t0 : 1
t1 : 1
t2 : 1
t3 : 1
t4 : 1
t0 : 2
t1 : 2
t2 : 2
t3 : 2
t4 : 2
t0 : 3
t1 : 3
t2 : 3
t3 : 3
t4 : 3
t0 : 4
t1 : 4
t2 : 4
t3 : 4
t4 : 4
由于代码(2)每次都是用一个新的TestThread对象来产生Thread对象的,所以产生出来的Thread对象是不同对象的线程,所以所有Thread对象都可同时访问run()函数。如果注释掉代码(2),并去掉代码(1)的注释,结果为:
t0 : 0
t0 : 1
t0 : 2
t0 : 3
t0 : 4
t1 : 0
t1 : 1
t1 : 2
t1 : 3
t1 : 4
t2 : 0
t2 : 1
t2 : 2
t2 : 3
t2 : 4
t3 : 0
t3 : 1
t3 : 2
t3 : 3
t3 : 4
t4 : 0
t4 : 1
t4 : 2
t4 : 3
t4 : 4
由于代码(1)中每次都是用同一个TestThread对象来产生Thread对象的,所以产生出来的Thread对象是同一个对象的线程,所以实现run()函数的同步。


二. 共享资源的同步
1. 同步的必要性
例4:

classSeq{
privatestaticintnumber = 0;
privatestaticSeq seq = newSeq();
privateSeq() {}
publicstaticSeq getInstance(){
returnseq;
}
publicintget(){
number++;  //(a)
returnnumber; //(b)
}
}
publicclassTestThread{
publicstaticvoidmain(java/lang/String.java.html" target="_blank">
String
[] args){
Seq.getInstance().get(); //(1)
Seq.getInstance().get(); //(2)
}
}

上面是一个取得序列号的单例模式的例子,但调用get()时,可能会产生两个相同的序列号:
当代码(1)和(2)都试图调用get()取得一个唯一的序列。当代码(1)执行完代码(a),正要执行代码(b)时,它被中断了并开始执行代码(2)。一旦当代码(2)执行完(a)而代码(1)还未执行代码(b),那么代码(1)和代码(2)就将得到相同的值。
2. 通过synchronized实现资源同步
2.1 锁标志
2.1.1每个对象都有一个标志锁。当对象的一个线程访问了对象的某个synchronized数据(包括函数)时,这个对象就将被“上锁”,所以被声明为synchronized的数据(包括函数)都不能被调用(因为当前线程取走了对象的“锁标志”)。只有当前线程访问完它要访问的synchronized数据,释放“锁标志”后,同一个对象的其它线程才能访问synchronized数据。
2.1.2 每个class也有一个“锁标志”。对于synchronized static数据(包括函数)可以在整个class下进行锁定,避免static数据的同时访问。
例5:

classSeq{
privatestaticintnumber = 0;
privatestaticSeq seq = newSeq();
privateSeq() {}
publicstaticSeq getInstance(){
returnseq;
}
publicsynchronizedintget(){ //(1)
number++;
returnnumber;
}
}

例5在例4的基础上,把get()函数声明为synchronized,那么在同一个对象中,就只能有一个线程调用get()函数,所以每个线程取得的number值就是唯一的了。
例6:

classSeq{
privatestaticintnumber = 0;
privatestaticSeq seq = null;
privateSeq() {}
synchronizedpublicstaticSeq getInstance(){ //(1)
if(seq==null) seq = newSeq();
returnseq;
}
publicsynchronizedintget(){
number++;
returnnumber;
}
}

例6把getInstance()函数声明为synchronized,那样就保证通过getInstance()得到的是同一个seq对象。
2.2 non-static的synchronized数据只能在同一个对象的纯种实现同步访问,不同对象的线程仍可同时访问。
例7:

classTestSynchronized implementsjava/lang/Runnable.java.html" target="_blank">
Runnable
{
publicsynchronizedvoidrun(){ //(1)
for(inti=0; i<10; i++){
java/lang/System.java.html" target="_blank">
System
.out.println(java/lang/Thread.java.html" target="_blank">
Thread
.currentThread().getName() + " : " + i);
/*(2)*/
try{
java/lang/Thread.java.html" target="_blank">
Thread
.sleep(100);
}
catch(java/lang/InterruptedException.java.html" target="_blank">
InterruptedException
e){
java/lang/System.java.html" target="_blank">
System
.out.println("Interrupted");
}
}
}
}
publicclassTestThread{
publicstaticvoidmain(java/lang/String.java.html" target="_blank">
String
[] args){
TestSynchronized r1 = newTestSynchronized();
TestSynchronized r2 = newTestSynchronized();
java/lang/Thread.java.html" target="_blank">
Thread
t1 = newjava/lang/Thread.java.html" target="_blank">
Thread
(r1, "t1");
java/lang/Thread.java.html" target="_blank">
Thread
t2 = newjava/lang/Thread.java.html" target="_blank">
Thread
(r2, "t2"); //(3)
//Thread t2 = new Thread(r1, "t2"); (4)
t1.start();
t2.start();
}
}

运行结果为:
t1 : 0
t2 : 0
t1 : 1
t2 : 1
t1 : 2
t2 : 2
t1 : 3
t2 : 3
t1 : 4
t2 : 4
t1 : 5
t2 : 5
t1 : 6
t2 : 6
t1 : 7
t2 : 7
t1 : 8
t2 : 8
t1 : 9
t2 : 9
虽然我们在代码(1)中把run()函数声明为synchronized,但由于t1、t2是两个对象(r1、r2)的线程,而run()函数是non-static的synchronized数据,所以仍可被同时访问(代码(2)中的sleep()函数由于在暂停时不会释放“标志锁”,因为线程中的循环很难被中断去执行另一个线程,所以代码(2)只是为了显示结果)。
如果把例7中的代码(3)注释掉,并去年代码(4)的注释,运行结果将为:
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
修改后的t1、t2是同一个对象(r1)的线程,所以只有当一个线程(t1或t2中的一个)执行run()函数,另一个线程才能执行。
2.3 对象的“锁标志”和class的“锁标志”是相互独立的。
例8:

classTestSynchronized extendsjava/lang/Thread.java.html" target="_blank">
Thread
{
publicTestSynchronized(java/lang/String.java.html" target="_blank">
String
name){
super(name);
}
publicsynchronizedstaticvoidprt(){
for(inti=10; i<20; i++){
java/lang/System.java.html" target="_blank">
System
.out.println(java/lang/Thread.java.html" target="_blank">
Thread
.currentThread().getName() + " : " + i);
try{
java/lang/Thread.java.html" target="_blank">
Thread
.sleep(100);
}
catch(java/lang/InterruptedException.java.html" target="_blank">
InterruptedException
e){
java/lang/System.java.html" target="_blank">
System
.out.println("Interrupted");
}
}
}
publicsynchronizedvoidrun(){
for(inti=0; i<10; i++){
java/lang/System.java.html" target="_blank">
System
.out.println(java/lang/Thread.java.html" target="_blank">
Thread
.currentThread().getName() + " : " + i);
try{
java/lang/Thread.java.html" target="_blank">
Thread
.sleep(100);
}
catch(java/lang/InterruptedException.java.html" target="_blank">
InterruptedException
e){
java/lang/System.java.html" target="_blank">
System
.out.println("Interrupted");
}
}
}
}
publicclassTestThread{
publicstaticvoidmain(java/lang/String.java.html" target="_blank">
String
[] args){
TestSynchronized t1 = newTestSynchronized("t1");
TestSynchronized t2 = newTestSynchronized("t2");
t1.start();
t1.prt(); //(1)
t2.prt(); //(2)
}
}

运行结果为:
main : 10
t1 : 0
main : 11
t1 : 1
main : 12
t1 : 2
main : 13
t1 : 3
main : 14
t1 : 4
main : 15
t1 : 5
main : 16
t1 : 6
main : 17
t1 : 7
main : 18
t1 : 8
main : 19
t1 : 9
main : 10
main : 11
main : 12
main : 13
main : 14
main : 15
main : 16
main : 17
main : 18
main : 19

在代码(1)中,虽然是通过对象t1来调用prt()函数的,但由于prt()是静态的,所以调用它时不用经过任何对象,它所属的线程为main线程。
由于调用run()函数取走的是对象锁,而调用prt()函数取走的是class锁,所以同一个线程t1(由上面可知实际上是不同线程)调用run()函数且还没完成run()函数时,它就能调用prt()函数。但prt()函数只能被一个线程调用,如代码(1)和代码(2),即使是两个不同的对象也不能同时调用prt()。
3. 同步的优化
1) synchronized block
语法为:synchronized(reference){ do this }
reference用来指定“以某个对象的锁标志”对“大括号内的代码”实施同步控制。
例9:

classTestSynchronized implementsjava/lang/Runnable.java.html" target="_blank">
Runnable
{
staticintj = 0;
publicsynchronizedvoidrun(){
for(inti=0; i<5; i++){
//(1)
java/lang/System.java.html" target="_blank">
System
.out.println(java/lang/Thread.java.html" target="_blank">
Thread
.currentThread().getName() + " : " + j++);
try{
java/lang/Thread.java.html" target="_blank">
Thread
.sleep(100);
}
catch(java/lang/InterruptedException.java.html" target="_blank">
InterruptedException
e){
java/lang/System.java.html" target="_blank">
System
.out.println("Interrupted");
}
}
}
}
publicclassTestThread{
publicstaticvoidmain(java/lang/String.java.html" target="_blank">
String
[] args){
TestSynchronized r1 = newTestSynchronized();
TestSynchronized r2 = newTestSynchronized();
java/lang/Thread.java.html" target="_blank">
Thread
t1 = newjava/lang/Thread.java.html" target="_blank">
Thread
(r1, "t1");
java/lang/Thread.java.html" target="_blank">
Thread
t2 = newjava/lang/Thread.java.html" target="_blank">
Thread
(r1, "t2");
t1.start();
t2.start();
}
}

运行结果为:
t1 : 0
t1 : 1
t1 : 2
t1 : 3
t1 : 4
t2 : 5
t2 : 6
t2 : 7
t2 : 8
t2 : 9
上面的代码的run()函数实现了同步,使每次打印出来的j总是不相同的。但实际上在整个run()函数中,我们只关心j的同步,而其余代码同步与否我们是不关心的,所以可以对它进行以下修改:

classTestSynchronized implementsjava/lang/Runnable.java.html" target="_blank">
Runnable
{
staticintj = 0;
publicvoidrun(){
for(inti=0; i<5; i++){
//(1)
synchronized(this){
java/lang/System.java.html" target="_blank">
System
.out.println(java/lang/Thread.java.html" target="_blank">
Thread
.currentThread().getName() + " : " + j++);
}
try{
java/lang/Thread.java.html" target="_blank">
Thread
.sleep(100);
}
catch(java/lang/InterruptedException.java.html" target="_blank">
InterruptedException
e){
java/lang/System.java.html" target="_blank">
System
.out.println("Interrupted");
}
}
}
}
publicclassTestThread{
publicstaticvoidmain(java/lang/String.java.html" target="_blank">
String
[] args){
TestSynchronized r1 = newTestSynchronized();
TestSynchronized r2 = newTestSynchronized();
java/lang/Thread.java.html" target="_blank">
Thread
t1 = newjava/lang/Thread.java.html" target="_blank">
Thread
(r1, "t1");
java/lang/Thread.java.html" target="_blank">
Thread
t2 = newjava/lang/Thread.java.html" target="_blank">
Thread
(r1, "t2");
t1.start();
t2.start();
}
}

运行结果为:
t1 : 0
t2 : 1
t1 : 2
t2 : 3
t1 : 4
t2 : 5
t1 : 6
t2 : 7
t1 : 8
t2 : 9
由于进行同步的范围缩小了,所以程序的效率将提高。同时,代码(1)指出,当对大括号内的println()语句进行同步控制时,会取走当前对象的“锁标志”,即对当前对象“上锁”,不让当前对象下的其它线程执行当前对象的其它synchronized数据。


三. 线程间的通信
1. 线程的几种状态
线程有四种状态,任何一个线程肯定处于这四种状态中的一种:
1) 产生(New):线程对象已经产生,但尚未被启动,所以无法执行。如通过new产生了一个线程对象后没对它调用start()函数之前。
2)可执行(Runnable):每个支持多线程的系统都有一个排程器,排程器会从线程池中选择一个线程并启动它。当一个线程处于可执行状态时,表示它可能正处于线程池中等待排排程器启动它;也可能它已正在执行。如执行了一个线程对象的start()方法后,线程就处于可执行状态,但显而易见的是此时线程不一定正在执行中。
3) 死亡(Dead):当一个线程正常结束,它便处于死亡状态。如一个线程的run()函数执行完毕后线程就进入死亡状态。
4)停滞(Blocked):当一个线程处于停滞状态时,系统排程器就会忽略它,不对它进行排程。当处于停滞状态的线程重新回到可执行状态时,它有可能重新执行。如通过对一个线程调用wait()函数后,线程就进入停滞状态,只有当两次对该线程调用notify或notifyAll后它才能两次回到可执行状态。
2. class Thread下的常用函数函数
2.1 suspend()、resume()
1) 通过suspend()函数,可使线程进入停滞状态。通过suspend()使线程进入停滞状态后,除非收到resume()消息,否则该线程不会变回可执行状态。
2) 当调用suspend()函数后,线程不会释放它的“锁标志”。
例11:
class TestThreadMethod extends Thread{
public static int shareVar = 0;
public TestThreadMethod(String name){
super(name);
}
public synchronized void run(){
if(shareVar==0){
for(int i=0; i<5; i++){
shareVar++;
if(shareVar==5){
this.suspend(); //(1)
}
}
}
else{
System.out.print(Thread.currentThread().getName());
System.out.println(" shareVar = " + shareVar);
this.resume(); //(2)
}
}
}
public class TestThread{
public static void main(String[] args){
TestThreadMethod t1 = new TestThreadMethod("t1");
TestThreadMethod t2 = new TestThreadMethod("t2");
t1.start(); //(5)
//t1.start(); //(3)
t2.start(); //(4)
}
}
运行结果为:
t2 shareVar = 5
i. 当代码(5)的t1所产生的线程运行到代码(1)处时,该线程进入停滞状态。然后排程器从线程池中唤起代码(4)的t2所产生的线程,此时shareVar值不为0,所以执行else中的语句。
ii.也许你会问,那执行代码(2)后为什么不会使t1进入可执行状态呢?正如前面所说,t1和t2是两个不同对象的线程,而代码(1)和(2)都只对当前对象进行操作,所以t1所产生的线程执行代码(1)的结果是对象t1的当前线程进入停滞状态;而t2所产生的线程执行代码(2)的结果是把对象t2中的所有处于停滞状态的线程调回到可执行状态。
iii.那现在把代码(4)注释掉,并去掉代码(3)的注释,是不是就能使t1重新回到可执行状态呢?运行结果是什么也不输出。为什么会这样呢?也许你会认为,当代码(5)所产生的线程执行到代码(1)时,它进入停滞状态;而代码(3)所产生的线程和代码(5)所产生的线程是属于同一个对象的,那么就当代码(3)所产生的线程执行到代码(2)时,就可使代码(5)所产生的线程执行回到可执行状态。但是要清楚,suspend()函数只是让当前线程进入停滞状态,但并不释放当前线程所获得的“锁标志”。所以当代码(5)所产生的线程进入停滞状态时,代码(3)所产生的线程仍不能启动,因为当前对象的“锁标志”仍被代码(5)所产生的线程占有。
2.2 sleep()
1) sleep ()函数有一个参数,通过参数可使线程在指定的时间内进入停滞状态,当指定的时间过后,线程则自动进入可执行状态。
2) 当调用sleep ()函数后,线程不会释放它的“锁标志”。
例12:
class TestThreadMethod extends Thread{
class TestThreadMethod extends Thread{
public static int shareVar = 0;
public TestThreadMethod(String name){
super(name);
}
public synchronized void run(){
for(int i=0; i<3; i++){
System.out.print(Thread.currentThread().getName());
System.out.println(" : " + i);
try{
Thread.sleep(100); //(4)
}
catch(InterruptedException e){
System.out.println("Interrupted");
}
}
}
}
public class TestThread{
public static void main(String[] args){
TestThreadMethod t1 = new TestThreadMethod("t1");
TestThreadMethod t2 = new TestThreadMethod("t2");
t1.start(); (1)
t1.start(); (2)
//t2.start(); (3)
}
}
运行结果为:
t1 : 0
t1 : 1
t1 : 2
t1 : 0
t1 : 1
t1 : 2
由结果可证明,虽然在run()中执行了sleep(),但是它不会释放对象的“锁标志”,所以除非代码(1)的线程执行完run()函数并释放对象的“锁标志”,否则代码(2)的线程永远不会执行。
如果把代码(2)注释掉,并去掉代码(3)的注释,结果将变为:
t1 : 0
t2 : 0
t1 : 1
t2 : 1
t1 : 2
t2 : 2
由于t1和t2是两个对象的线程,所以当线程t1通过sleep()进入停滞时,排程器会从线程池中调用其它的可执行线程,从而t2线程被启动。
例13:
class TestThreadMethod extends Thread{
public static int shareVar = 0;
public TestThreadMethod(String name){
super(name);
}
public synchronized void run(){
for(int i=0; i<5; i++){
System.out.print(Thread.currentThread().getName());
System.out.println(" : " + i);
try{
if(Thread.currentThread().getName().equals("t1"))
Thread.sleep(200);
else
Thread.sleep(100);
}
catch(InterruptedException e){
System.out.println("Interrupted");
}
}
}
}
public class TestThread{
public static void main(String[] args){
TestThreadMethod t1 = new TestThreadMethod("t1");
TestThreadMethod t2 = new TestThreadMethod("t2");
t1.start();
//t1.start();
t2.start();
}
}
运行结果为:
t1 : 0
t2 : 0
t2 : 1
t1 : 1
t2 : 2
t2 : 3
t1 : 2
t2 : 4
t1 : 3
t1 : 4
由于线程t1调用了sleep(200),而线程t2调用了sleep(100),所以线程t2处于停滞状态的时间是线程t1的一半,从从结果反映出来的就是线程t2打印两倍次线程t1才打印一次。
2.3 yield()
1) 通过yield ()函数,可使线程进入可执行状态,排程器从可执行状态的线程中重新进行排程。所以调用了yield()的函数也有可能马上被执行。
2) 当调用yield ()函数后,线程不会释放它的“锁标志”。
例14:
class TestThreadMethod extends Thread{
public static int shareVar = 0;
public TestThreadMethod(String name){
super(name);
}
public synchronized void run(){
for(int i=0; i<4; i++){
System.out.print(Thread.currentThread().getName());
System.out.println(" : " + i);
Thread.yield();
}
}
}
public class TestThread{
public static void main(String[] args){
TestThreadMethod t1 = new TestThreadMethod("t1");
TestThreadMethod t2 = new TestThreadMethod("t2");
t1.start();
t1.start(); //(1)
//t2.start(); (2)
}
}
运行结果为:
t1 : 0
t1 : 1
t1 : 2
t1 : 3
t1 : 0
t1 : 1
t1 : 2
t1 : 3
从结果可知调用yield()时并不会释放对象的“锁标志”。
如果把代码(1)注释掉,并去掉代码(2)的注释,结果为:
t1 : 0
t1 : 1
t2 : 0
t1 : 2
t2 : 1
t1 : 3
t2 : 2
t2 : 3
从结果可知,虽然t1线程调用了yield(),但它马上又被执行了。
2.4 sleep()和yield()的区别
1) sleep()使当前线程进入停滞状态,所以执行sleep()的线程在指定的时间内肯定不会执行;yield()只是使当前线程重新回到可执行状态,所以执行yield()的线程有可能在进入到可执行状态后马上又被执行。
2) sleep()可使优先级低的线程得到执行的机会,当然也可以让同优先级和高优先级的线程有执行的机会;yield()只能使同优先级的线程有执行的机会。
例15:
class TestThreadMethod extends Thread{
public static int shareVar = 0;
public TestThreadMethod(String name){
super(name);
}
public void run(){
for(int i=0; i<4; i++){
System.out.print(Thread.currentThread().getName());
System.out.println(" : " + i);
//Thread.yield(); (1)
/* (2) */
try{
Thread.sleep(3000);
}
catch(InterruptedException e){
System.out.println("Interrupted");
}

}
}
}
public class TestThread{
public static void main(String[] args){
TestThreadMethod t1 = new TestThreadMethod("t1");
TestThreadMethod t2 = new TestThreadMethod("t2");
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
}
}
运行结果为:
t1 : 0
t1 : 1
t2 : 0
t1 : 2
t2 : 1
t1 : 3
t2 : 2
t2 : 3
由结果可见,通过sleep()可使优先级较低的线程有执行的机会。注释掉代码(2),并去掉代码(1)的注释,结果为:
t1 : 0
t1 : 1
t1 : 2
t1 : 3
t2 : 0
t2 : 1
t2 : 2
t2 : 3
可见,调用yield(),不同优先级的线程永远不会得到执行机会。
2.5 join()
使调用join()的线程执行完毕后才能执行其它线程,在一定意义上,它可以实现同步的功能。
例16:
class TestThreadMethod extends Thread{
public static int shareVar = 0;
public TestThreadMethod(String name){
super(name);
}
public void run(){
for(int i=0; i<4; i++){
System.out.println(" " + i);
try{
Thread.sleep(3000);
}
catch(InterruptedException e){
System.out.println("Interrupted");
}
}
}
}
public class TestThread{
public static void main(String[] args){
TestThreadMethod t1 = new TestThreadMethod("t1");
t1.start();
try{
t1.join();
}
catch(InterruptedException e){}
t1.start();
}
}
运行结果为:
0
1
2
3
0
1
2
3


3. class Object下常用的线程函数
wait()、notify()和notifyAll()这三个函数由java.lang.Object类提供,用于协调多个线程对共享数据的存取。
3.1 wait()、notify()和notifyAll()
1) wait()函数有两种形式:第一种形式接受一个毫秒值,用于在指定时间长度内暂停线程,使线程进入停滞状态。第二种形式为不带参数,代表waite()在notify()或notifyAll()之前会持续停滞。
2) 当对一个对象执行notify()时,会从线程等待池中移走该任意一个线程,并把它放到锁标志等待池中;当对一个对象执行notifyAll()时,会从线程等待池中移走所有该对象的所有线程,并把它们放到锁标志等待池中。
3) 当调用wait()后,线程会释放掉它所占有的“锁标志”,从而使线程所在对象中的其它synchronized数据可被别的线程使用。
例17:
下面,我们将对例11中的例子进行修改
class TestThreadMethod extends Thread{
public static int shareVar = 0;
public TestThreadMethod(String name){
super(name);
}
public synchronized void run(){
if(shareVar==0){
for(int i=0; i<10; i++){
shareVar++;
if(shareVar==5){
try{
this.wait(); //(4)
}
catch(InterruptedException e){}
}
}
}
if(shareVar!=0){
System.out.print(Thread.currentThread().getName());
System.out.println(" shareVar = " + shareVar);
this.notify(); //(5)
}
}
}
public class TestThread{
public static void main(String[] args){
TestThreadMethod t1 = new TestThreadMethod("t1");
TestThreadMethod t2 = new TestThreadMethod("t2");
t1.start(); //(1)
//t1.start(); (2)
t2.start(); //(3)
}
}
运行结果为:
t2 shareVar = 5
因为t1和t2是两个不同对象,所以线程t2调用代码(5)不能唤起线程t1。如果去掉代码(2)的注释,并注释掉代码(3),结果为:
t1 shareVar = 5
t1 shareVar = 10
这是因为,当代码(1)的线程执行到代码(4)时,它进入停滞状态,并释放对象的锁状态。接着,代码(2)的线程执行run(),由于此时shareVar值为5,所以执行打印语句并调用代码(5)使代码(1)的线程进入可执行状态,然后代码(2)的线程结束。当代码(1)的线程重新执行后,它接着执行for()循环一直到shareVar=10,然后打印shareVar。
3.2 wait()、notify()和synchronized
waite()和notify()因为会对对象的“锁标志”进行操作,所以它们必须在synchronized函数或synchronized block中进行调用。如果在non-synchronized函数或non-synchronized block中进行调用,虽然能编译通过,但在运行时会发生IllegalMonitorStateException的异常。
例18:
class TestThreadMethod extends Thread{
public int shareVar = 0;
public TestThreadMethod(String name){
super(name);
new Notifier(this);
}
public synchronized void run(){
if(shareVar==0){
for(int i=0; i<5; i++){
shareVar++;
System.out.println("i = " + shareVar);
try{
System.out.println("wait......");
this.wait();
}
catch(InterruptedException e){}
}
}
}
}
class Notifier extends Thread{
private TestThreadMethod ttm;
Notifier(TestThreadMethod t){
ttm = t;
start();
}
public void run(){
while(true){
try{
sleep(2000);
}
catch(InterruptedException e){}
/*1 要同步的不是当前对象的做法 */
synchronized(ttm){
System.out.println("notify......");
ttm.notify();
}
}
}
}
public class TestThread{
public static void main(String[] args){
TestThreadMethod t1 = new TestThreadMethod("t1");
t1.start();
}
}
运行结果为:
i = 1
wait......
notify......
i = 2
wait......
notify......
i = 3
wait......
notify......
i = 4
wait......
notify......
i = 5
wait......
notify......
4. wait()、notify()、notifyAll()和suspend()、resume()、sleep()的讨论
4.1 这两组函数的区别
1) wait()使当前线程进入停滞状态时,还会释放当前线程所占有的“锁标志”,从而使线程对象中的synchronized资源可被对象中别的线程使用;而suspend()和sleep()使当前线程进入停滞状态时不会释放当前线程所占有的“锁标志”。
2) 前一组函数必须在synchronized函数或synchronized block中调用,否则在运行时会产生错误;而后一组函数可以non-synchronized函数和synchronized block中调用。
4.2 这两组函数的取舍
Java2已不建议使用后一组函数。因为在调用wait()时不会释放当前线程所取得的“锁标志”,这样很容易造成“死锁”。

原创粉丝点击