Java多线程核心技术(三):线程间通信

来源:互联网 发布:网络优化工程师培训费 编辑:程序博客网 时间:2024/05/24 03:21

一、等待/通知机制

1、wait()/notify()

方法wait()的作用是使当前执行代码的线程进行等待,wait()方法是Object类的方法,该方法用来将当前线程置入“预执行队列”中,并且在wait()所在的代码行处停止执行,直到接到通知或被中断为止。在调用wait()方法之前,线程必须获得该对象的对象级别锁,即只能在同步方法或者同步块中调用wait()方法。如果调用wait()时没有持有适当的锁,则抛出IllegalMonitorStateException,它是RuntimeException的一个子类,因此不需要try-catch语句进行捕捉异常。

方法notify()的作用是用来通知那些可能等待该对象的对象锁的其他线程,如果有多个线程等待,则由线程规划器随机挑选出其中一个呈wait状态的线程,对其发出通知notify,并 使它等待获取该对象的对象锁。notify()也要在同步方法或者同步块中调用,即在调用前,线程也必须获得该对象的对象级别锁。如果调用notify()时没有持有适当的锁,也会抛出IllegalMonitorStateException 异常。

调用notify()一次只随机通知一个线程进行唤醒。notifyAll()方法可以唤醒全部线程。

注意:

(1)当线程呈wait()状态时,调用线程对象的interrupt()方法会出现InterruptedException异常。

(2)在执行同步块代码的过程中,遇到异常而导致线程终止,锁也会被释放。

(3)在执行wait()方法后,当前线程会立即释放锁,但在执行notify()方法后,当前线程不会马上释放该对象的锁,要等到执行notify()方法的线程将程序执行完,也就是退出synchronized代码块后,当前线程才会释放锁。代码示例如下:

class Service{public void testMethod(Object lock){try{synchronized(lock){System.out.println("begin wait() ThreadName = " + Thread.currentThread().getName());lock.wait();System.out.println("  end wait() ThreadName = " + Thread.currentThread().getName());}}catch(InterruptedException e){e.printStackTrace();}}public void synNotifyMethod(Object lock){try{synchronized(lock){System.out.println("begin notify() ThreadName = " + Thread.currentThread().getName() + " time = "+System.currentTimeMillis());lock.notify();Thread.sleep(5000);System.out.println("  end notify() ThreadName = " + Thread.currentThread().getName() + " time = "+System.currentTimeMillis());}}catch(InterruptedException e){e.printStackTrace();}}}class Mythread extends Thread{private Object lock;public Mythread(Object lock){this.lock = lock;}@Overridepublic void run(){Service service = new Service();service.testMethod(lock);}}class NotifyThread extends Thread{private Object lock;public NotifyThread(Object lock){this.lock = lock;}@Overridepublic void run(){Service service = new Service();service.synNotifyMethod(lock);}}public class TestClass{public static void main(String[] args) throws InterruptedException{Object lock = new Object();Mythread t = new Mythread(lock);t.start();NotifyThread notifyThread = new NotifyThread(lock);notifyThread.start();}}
程序运行结果如下:


wait(long)方法的功能是等待某一时间内是否有线程对锁进行唤醒,如果超过这个时间则自动唤醒。

2、通过管道进行线程间通信

管道流是一种特殊的流,用于在不同线程间直接传送数据。一个线程发送数据到输出管道,另一个线程从输入管道中读数据。通过使用管道,实现不同线程间的通信,而无须借助于类似临时文件之类的东西。

在Java的JDK中提供了4个类来使线程间可以进行通信:

(1)PipedInputStream和PipedOutputStream

(2)PipedReader和PipedWriter

以下代码是PipedReader和PipedWriter(PipedInputStream和PipedOutputStream的用法是一样的)使用的示例代码:

import java.io.IOException;import java.io.PipedReader;import java.io.PipedWriter;class WriteData{public void writeMethod(PipedWriter out){try{System.out.println("write:");for(int i = 0 ;i < 10; i++){String outData = " " + i;out.write(outData);System.out.print(outData);}System.out.println();out.close();}catch(IOException e){e.printStackTrace();}}}class ReadData{public void readMethod(PipedReader input){try{System.out.println("read:");char[] byteArray = new char[20];int readLength = input.read(byteArray);while(readLength != -1){String newData = new String(byteArray,0,readLength);System.out.print(newData);readLength = input.read(byteArray);}System.out.println();input.close();}catch(IOException e){e.printStackTrace();}}}class ThreadWrite extends Thread{private WriteData write;private PipedWriter out;public ThreadWrite(WriteData write,PipedWriter out){this.write = write;this.out = out;}@Overridepublic void run(){write.writeMethod(out);}}class ThreadRead extends Thread{private ReadData read;private PipedReader input;public ThreadRead(ReadData read,PipedReader input){this.read = read;this.input = input;}@Overridepublic void run(){read.readMethod(input);}}public class TestClass{public static void main(String[] args){try{WriteData writeData = new WriteData();ReadData readData = new ReadData();PipedReader reader = new PipedReader();PipedWriter writer = new PipedWriter();writer.connect(reader);ThreadRead read = new ThreadRead(readData,reader);read.start();ThreadWrite write = new ThreadWrite(writeData,writer);write.start();}catch(IOException e){e.printStackTrace();}}}
下图是运行结果:

二、方法join的使用

方法join()的作用是使所属的线程对象正常执行run()方法中的任务,而使当前线程z进行无限期的阻塞,等待线程x销毁后再继续线程z后面的代码。一以下代码可以实现主线程等待子线程执行完毕再打印:

class MyThread extends Thread{@Overridepublic void run(){try {int secondValue = (int)(Math.random() * 10000);Thread.sleep(secondValue);System.out.println(secondValue);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public class TestClass{public static void main(String[] args){try{MyThread threadTest = new MyThread();threadTest.start();threadTest.join();System.out.println("我想当threadTest对象执行完毕后我再执行,我做到了!");}catch(InterruptedException e){e.printStackTrace();}}}

主线程会在子线程打印出随机时间之后在打印:


在join过程中,如果当前线程对象被中断,则当前线程出现异常,其他线程正常执行。

join(long)与sleep(long)的区别:

方法join(long)的功能在内部是使用wait(long)方法来实现的,所以join(long)方法具有释放锁的特点。而Thread.sleep(long)方法却不释放锁。如下代码示例可以展现两者的区别:

class ThreadB extends Thread{@Overridepublic void run(){try{System.out.println(" b run begin timer = " + System.currentTimeMillis());Thread.sleep(5000);System.out.println(" b run   end timer = " + System.currentTimeMillis());}catch(InterruptedException e){e.printStackTrace();}}synchronized public void bService(){System.out.println("打印了bService timer = " + System.currentTimeMillis());}}class ThreadA extends Thread{private ThreadB b;public ThreadA(ThreadB b){this.b = b;}@Overridepublic void run(){try{synchronized(b){b.start();Thread.sleep(6000);//b.join(6000);}}catch(InterruptedException e){e.printStackTrace();}}}class ThreadC extends Thread{private ThreadB b;public ThreadC(ThreadB b){this.b = b;}@Overridepublic void run(){b.bService();}}public class TestClass{public static void main(String[] args){ThreadB b = new ThreadB();ThreadA a = new ThreadA(b);a.start();ThreadC c = new ThreadC(b);c.start();}}


由于线程ThreadA使用Thread.sleep(long)方法一直持有ThreadB对象的锁,时间达到6秒,所以线程ThreadC只有在ThreadA时间到达6秒释放ThreadB的锁时,才可以调用ThreadB的同步方法synchronized public void bService()。把上面代码的Thread.sleep(6000);换成b.join(6000),则结果如下所示:


使用join方法后,由于线程ThreadA释放了ThreadB的锁,所以线程ThreadC可以调用ThreadB中的同步方法synchronized public void bService()。

三、类ThreadLocal的使用

类ThreadLocal主要解决的就是每个线程绑定自己的值。ThreadLocal的get()方法放回与本线程相关的值,set()方法将与本线程相关的值绑定。第一次调用ThreadLocal类的get()方法返回值是null。

四、类InheritableThreadLocal的使用

使用InheritableThreadLocal类可以让子线程从父线程中取得值。如下代码所示:

class InheritableThreadLocalExt extends InheritableThreadLocal<Object>{@Overrideprotected Object initialValue(){return "你好!";}}class ThreadA extends Thread{@Overridepublic void run(){System.out.println("ThreadA中的值=" + TestClass.ext.get());}}public class TestClass{public static InheritableThreadLocalExt ext = new InheritableThreadLocalExt();public static void main(String[] args){System.out.println("Main中的值=" + TestClass.ext.get());ThreadA a = new ThreadA();a.setName("ThreadA");a.start();}}
运行结果如下:

注意:如果子线程在取值的同时,主线程将InheritableThreadLocal中的值进行更改,那么子线程取到的值还是旧值。

1 0