前文:java 线程与进程基础、java 锁、java 线程池
-
线程通信
在java 线程与进程基础中我们讲过进程同步,而进程同步问题中有一个非常典型的生产者-消费者问题:当队列满时,生产者需要等待队列有空间才能继续往里面放入商品,而在等待的期间内,生产者必须释放对临界资源(即队列)的占用权。因为生产者如果不释放对临界资源的占用权,那么消费者就无法消费队列中的商品,就不会让队列有空间,那么生产者就会一直无限等待下去。因此一般情况下,当队列满时,会让生产者交出对临界资源的占用权,并进入挂起状态。然后等待消费者消费了商品,然后消费者通知生产者队列有空间了。同样地,当队列空时,消费者也必须等待,等待生产者通知它队列中有商品了。我们可以通过以下几种方式解决这个问题:-
synchronized+wait-notify模式
class MyRun { private String lock = new String(""); public Runnable runnableA = new Runnable() { @Override public void run() { try { synchronized (lock) { System.out.println("begin wait"); lock.wait(); System.out.println("end wait"); } } catch (InterruptedException e) { e.printStackTrace(); } } }; public Runnable runnableB = new Runnable() { @Override public void run() { synchronized (lock) { System.out.println("begin notify"); lock.notify(); System.out.println("end notify"); } }
public static void main(String[] args) throws InterruptedException { MyRun run = new MyRun(); Thread bThread = new Thread(run.runnableA); bThread.start(); Thread aThread = new Thread(run.runnableB); aThread.start(); }
- 使用
- wait()方法: 让当前线程进入等待,并释放锁。
- wait(long)方法: 让当前线程进入等待,并释放锁,不过等待时间为long,超过这个时间没有对当前线程进行唤醒,将自动唤醒。
- notify()方法: 让当前线程通知那些处于等待状态的线程,当前线程执行完毕后释放锁,并从其他线程中唤醒其中一个继续执行。该方法有可能会造成死锁。
- notifyAll()方法: 让当前线程通知那些处于等待状态的线程,当前线程执行完毕后释放锁,将唤醒所有等待状态的线程。
- 注意事项
-
当前的线程必须拥有当前对象的monitor,也即锁,才能调用wait()方法,否则将抛出异常java.lang.IllegalMonitorStateException。
-
线程调用wait()方法,释放它对锁的拥有权,然后等待另外的线程来通知它(通知的方式是notify()或者notifyAll()方法),这样它才能重新获得锁的拥有权和恢复执行。
-
要确保调用wait()方法的时候拥有锁,即,wait()方法的调用必须放在synchronized方法或synchronized块中。
-
如果多个线程在等待,它们中的一个将会选择被唤醒。这种选择是随意的,和具体实现有关。(线程等待一个对象的锁是由于调用了wait()方法)。
-
被唤醒的线程是不能被执行的,需要等到当前线程放弃这个对象的锁,当前线程会在方法执行完毕后释放锁。
-
如果notify()方法先执行,将导致wait()方法释放锁进入等待状态后,永远无法被唤醒,影响程序逻辑。应避免这种情况。
-
如果wait等待条件发生了变化,也容易造成程序逻辑的混乱。
-
- 使用
-
Lock+Condition模式
在Lock+Condition模式中,主要由Condition实现等待/通知模式,使用方式与注意方式与wait/notify一样,我们可以简单的这样理解:
使用Condition往往比使用synchronized+wait-notify要更灵活、高效,例如,我们可以使用多个Condition实现通知部分线程:// 线程 A class ThreadA extends Thread { private MyService service; public ThreadA(MyService service) { super(); this.service = service; } @Override public void run() { service.awaitA(); } } // 线程 B class ThreadB extends Thread { public ThreadB(MyService service) { super(); this.service = service; } @Override public void run() { service.awaitB(); } } class MyService { private Lock lock = new ReentrantLock(); // 使用多个Condition实现通知部分线程 public Condition conditionA = lock.newCondition(); public Condition conditionB = lock.newCondition(); public void awaitA() { lock.lock(); try { System.out.println("begin awaitA时间为" + System.currentTimeMillis() + " ThreadName=" + Thread.currentThread().getName()); conditionA.await(); System.out.println(" end awaitA时间为" + System.currentTimeMillis() + " ThreadName=" + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void awaitB() { lock.lock(); try { System.out.println("begin awaitB时间为" + System.currentTimeMillis() + " ThreadName=" + Thread.currentThread().getName()); conditionB.await(); System.out.println(" end awaitB时间为" + System.currentTimeMillis() + " ThreadName=" + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void signalAll_A() { try { lock.lock(); System.out.println(" signalAll_A时间为" + System.currentTimeMillis() + " ThreadName=" + Thread.currentThread().getName()); conditionA.signalAll(); } finally { lock.unlock(); } } public void signalAll_B() { try { lock.lock(); System.out.println(" signalAll_B时间为" + System.currentTimeMillis() + " ThreadName=" + Thread.currentThread().getName()); conditionB.signalAll(); } finally { lock.unlock(); } } } // 测试 public class Run { public static void main(String[] args) throws InterruptedException { MyService service = new MyService(); ThreadA a = new ThreadA(service); a.setName("A"); a.start(); ThreadB b = new ThreadB(service); b.setName("B"); b.start(); Thread.sleep(3000); service.signalAll_A(); } }
输出结果:
begin awaitA时间为1486711220139 ThreadName=A begin awaitB时间为1486711220143 ThreadName=B signalAll awaitA时间为148671133139 ThreadName=main end awaitA时间为1486711333139 ThreadName=A
我们可以看到只有A被唤醒,线程B仍然阻塞。这就是Condition的特殊之处:synchronized相当于整个ReentrantLock对象只有一个单一的Condition对象情况。而一个ReentrantLock却可以拥有多个Condition对象,来实现通知部分线程。
-
-
管道
管道输入/输出流和普通的文件输入/输出流或者网络输入/输出流不同之处在于,它主要用于线程之间的数据传输,而传输的媒介为内存。管道输入/输出流主要包括了如下4种具体实现:PipedOutputStream、PipedInputStream、PipedReader和PipedWriter,前两种面向字节,而后两种面向字符。
举个🌰://读出数据线程 class ThreadRead extends Thread { private ReadData read; private PipedInputStream input; public ThreadRead(ReadData read, PipedInputStream input) { super(); this.read = read; this.input = input; } public void readMethod(PipedInputStream input) { try { System.out.println("read :"); byte[] byteArray = new byte[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(); } } @Override public void run() { this.readMethod(input); } } //写入数据线程 class ThreadWrite extends Thread { private WriteData write; private PipedOutputStream out; public ThreadWrite(WriteData write, PipedOutputStream out) { super(); this.write = write; this.out = out; } public void writeMethod(PipedOutputStream out) { try { System.out.println("write :"); for (int i = 0; i < 30; i++) { String outData = "" + (i + 1); out.write(outData.getBytes()); System.out.print(outData); } System.out.println(); out.close(); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { this.writeMethod(out); } } //测试 public class Run { public static void main(String[] args) { try { WriteData writeData = new WriteData(); ReadData readData = new ReadData(); PipedInputStream inputStream = new PipedInputStream(); PipedOutputStream outputStream = new PipedOutputStream(); // inputStream.connect(outputStream); // 效果相同 outputStream.connect(inputStream); ThreadRead threadRead = new ThreadRead(readData, inputStream); threadRead.start(); Thread.sleep(2000); ThreadWrite threadWrite = new ThreadWrite(writeData, outputStream); threadWrite.start(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
-
延伸:Join()
join方法是通过调用线程的wait方法来达到同步的目的的。例如A线程中调用了B线程的join方法,则相当于在A线程中调用了B线程的wait方法,当B线程执行完(或者到达等待时间),B线程会自动调用自身的notifyAll方法唤醒A线程,从而达到同步的目的。我们以join(long millis)方法为🌰:
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; } } }
通过上面的源码我们可以看到:
- 如果join方法传参为0的话,则会调用isAlive()方法,一直检测线程是否存活(执行完毕),如果存活就调用wait方法,一直阻塞。isAlive()判断线程是否还活着,即线程是否还未终止。
- 如果参数为负数,则直接报错:“timeout value is negative”
- 如果参数大于0,则while里面一直判断线程是否存活,存活的话就一直判断当前线程执行的时间并与计算还需要等待多久时间,最后如果等待时间小于等于0就跳出循环,否则就继续wait
经典面试题
现在有T1、T2、T3三个线程,你怎样保证T2在T1执行完后执行,T3在T2执行完后执行?
- 用join()
T1.start(); T1.join(); T2.start(); T2.join(); T3.start(); T3.join();
- 用锁
class ShareThread { // flag作为标记 private int flag = 1; private Lock lock = new ReentrantLock(); private Condition c1 = lock.newCondition(); private Condition c2 = lock.newCondition(); private Condition c3 = lock.newCondition(); public void Test01() throws InterruptedException { lock.lock(); try { while (flag != 1) { c1.await(); } System.out.println("正在执行的是:" + Thread.currentThread().getName()); flag = 2; c2.signal();// 通知一个线程来执行 } finally { lock.unlock(); } } public void Test02() throws InterruptedException { lock.lock(); try { while (flag != 2) { c2.await(); } System.out.println("正在执行的是:" + Thread.currentThread().getName()); flag = 3; c3.signal();// 通知一个线程来执行 } finally { lock.unlock(); } } public void Test03() throws InterruptedException { lock.lock(); try { while (flag != 3) { c3.await(); } System.out.println("正在执行的是:" + Thread.currentThread().getName()); flag = 1; c1.signal();// 通知一个线程来执行 } finally { lock.unlock(); } } }