Java多线程编程(三)线程间通信

时间:2022-10-31 13:49:14

  线程是操作系统中独立的个体,但这些个体如果不经过特殊的处理就不能成为一个整体。线程间的通信就是成为整体的必用方案之一,可以说,使线程间进行通信后,系统之间的交互性会更强大,在大大提高CPU利用率的同时还会使程序员对各线程任务在处理的过程中进行有效地把控与监督。  

  一、等待/通知机制

  1.不使用等待/通知机制实现线程间通信

  示例:线程A向数组中增加元素,线程B不断查询数组中元素个数,在元素个数等于1时发生异常并停止。虽然两个线程实现了通信,但有一个弊端就是,线程B不停地通过while语句轮询机制来检测某一个条件,这样会浪费CPU资源。如果轮询的时间间隔很小,更浪费CPU资源;如果轮询的时间间隔很大,有可能会取不到想要得到的数据。所以就需要有一种机制来减少CPU资源的浪费,而且还可以实现在多个线程间通信,它就是“wait/notify”机制。

package mylist;

import java.util.ArrayList;
import java.util.List; public class MyList { private List<Integer> list = new ArrayList<Integer>(); public void add() {
list.add(1);
} public int size() {
return list.size();
} }
package extthread;

import mylist.MyList;

public class ThreadA extends Thread {

    private MyList list;

    public ThreadA(MyList list) {
super();
this.list = list;
} @Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
list.add();
System.out.println("添加了" + (i + 1) + "个元素!");
System.out.println(list.size());
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
package extthread;

import mylist.MyList;

public class ThreadB extends Thread {

    private MyList list;

    public ThreadB(MyList list) {
super();
this.list = list;
} @Override
public void run() {
System.out.println("B");
try {
while (true) {
if (list.size() == 1) {
System.out.println("==1了,线程b要退出了!");
throw new InterruptedException();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
package test;

import mylist.MyList;
import extthread.ThreadA;
import extthread.ThreadB; public class Test { public static void main(String[] args) {
MyList service = new MyList(); ThreadA a = new ThreadA(service);
a.setName("A");
a.start(); ThreadB b = new ThreadB(service);
b.setName("B");
b.start(); } }
添加了1个元素!
1
B
==1了,线程b要退出了!
java.lang.InterruptedException
at extthread.ThreadB.run(ThreadB.java:21)
添加了2个元素!
2
添加了3个元素!
3
...

  2.什么是等待/通知机制

  等待/通知机制用厨师和服务员的交互来解释:

  (1)厨师做完一道菜的时间不确定,所以厨师将菜品放到“传菜台”上的时间也不确定。

  (2)服务员取到菜的时间取决于厨师,所以服务员就有“等待”的状态。

  (3)厨师将菜放在“传菜苔”上,服务员才能取到菜,这就相当于一种“通知”,这时服务员才可以拿到菜并交给就餐者。

  前面介绍的多个线程之间的通信,原因是多个线程共同访问同一个变量,但那种通信机制不是等待/通知机制,两个线程完全是主动式地读取一个共享变量,在花费读取时间的基础上,读到的值是不是想要的,并不能完全确定。等待/通知机制可以解决这些问题。

  3.等待/通知机制的实现

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

  方法notify()的作用:也要在同步方法或同步块中调用,即在调用前,线程也必须获得该对象的对象级别锁。如调用notify()时没有持有适当的锁,也会抛出IllegalMonitorStateException。该方法用来通知那些可能等待该对象的对象锁的其他线程,如果有多个线程等待,则由线程规划器随机挑选出其中一个呈wait状态的线程,对其发出通知notify,并使它等待获取该对象的对象锁。需要说明的是,在执行notify()方法后,当前线程不会马上释放该对象锁,呈wait状态的线程也并不能马上获取该对象锁,到等到执行notify()方法的线程将程序执行完,也就是退出synchronized代码块后,当前线程才会释放锁,而呈wait状态所在的线程才可以获取该对象锁。当第一个获得了该对象锁的wait线程运行完毕以后,它会释放掉该对象锁,此时如果该对象没有再次使用notify语句,则即便该对象已经空闲,其他wait状态等待的线程由于没有得到该对象的通知,还会继续阻塞在wait状态,直到这个对象发出一个notify或notifyAll。

  总结:wait使线程停止运行,而notify使停止的线程继续运行。

  示例1:没有对newString加对象级别锁,没有“对象监视器”,也就是没有同步加锁,所以出现异常。

package test;

public class Test1 {
public static void main(String[] args) {
try {
String newString = new String("");
newString.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Exception in thread "main" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Unknown Source)
at test.Test1.main(Test1.java:7)

  示例2:获得对象锁后,不再抛出异常,从输出结果可以看出,wait()方法后面的代码都不执行了,使用notify()方法可以使等待wait状态的线程继续运行。

package test;

public class Test2 {

    public static void main(String[] args) {
try {
String lock = new String();
System.out.println("syn上一行");
synchronized (lock) {
System.out.println("syn第一行");
lock.wait();
System.out.println("wait下面一行");
}
System.out.println("syn代码块下面的一行");
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
syn上一行
syn第一行

  示例3:线程A运行时呈wait状态,等待3秒后,线程B通过调用notify()方法将线程A唤醒。

package extthread;

public class MyThread1 extends Thread {
private Object lock; public MyThread1(Object lock) {
super();
this.lock = lock;
} @Override
public void run() {
try {
synchronized (lock) {
System.out.println("开始 wait time=" + System.currentTimeMillis());
lock.wait();
System.out.println("结束 wait time=" + System.currentTimeMillis());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package extthread;

public class MyThread2 extends Thread {
private Object lock; public MyThread2(Object lock) {
super();
this.lock = lock;
} @Override
public void run() {
synchronized (lock) {
System.out.println("开始notify time=" + System.currentTimeMillis());
lock.notify();
System.out.println("结束notify time=" + System.currentTimeMillis());
}
}
}
package test;

import extthread.MyThread1;
import extthread.MyThread2; public class Test {
public static void main(String[] args) {
try {
Object lock = new Object(); MyThread1 t1 = new MyThread1(lock);
t1.start(); Thread.sleep(3000); MyThread2 t2 = new MyThread2(lock);
t2.start(); } catch (InterruptedException e) {
e.printStackTrace();
}
}
}

  示例4:从输出可以看出,wait end在最后输出,这说明notify()方法执行后并不立即释放锁。

package extlist;

import java.util.ArrayList;
import java.util.List; public class MyList { private static List<String> list = new ArrayList<String>(); public static void add() {
list.add("anyString");
} public static int size() {
return list.size();
} }
package extthread;

import extlist.MyList;

public class ThreadA extends Thread {

    private Object lock;

    public ThreadA(Object lock) {
super();
this.lock = lock;
} @Override
public void run() {
try {
synchronized (lock) {
if (MyList.size() != 5) {
System.out.println("wait begin "+ System.currentTimeMillis());
lock.wait();
System.out.println("wait end "+ System.currentTimeMillis());
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
package extthread;

import extlist.MyList;

public class ThreadB extends Thread {
private Object lock; public ThreadB(Object lock) {
super();
this.lock = lock;
} @Override
public void run() {
try {
synchronized (lock) {
for (int i = 0; i < 10; i++) {
MyList.add();
if (MyList.size() == 5) {
lock.notify();
System.out.println("已发出通知!");
}
System.out.println("添加了" + (i + 1) + "个元素!");
Thread.sleep(1000);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
package test;

import extthread.ThreadA;
import extthread.ThreadB; public class Run { public static void main(String[] args) { try {
Object lock = new Object(); ThreadA a = new ThreadA(lock);
a.start(); Thread.sleep(50); ThreadB b = new ThreadB(lock);
b.start();
} catch (InterruptedException e) {
e.printStackTrace();
} } }
wait begin 1525504132043
添加了1个元素!
添加了2个元素!
添加了3个元素!
添加了4个元素!
已发出通知!
添加了5个元素!
添加了6个元素!
添加了7个元素!
添加了8个元素!
添加了9个元素!
添加了10个元素!
wait end 1525504142153

  总结:

  关键字synchronized可以将任何一个Object对象作为同步对象来看待,而Java为每个Object都实现了wait()和notify()方法,它们必须用在被synchronized同步的Object的临界区内。通过调用wait()方法可以使处于临界区内的线程进入等待状态,同时释放被同步对象的锁。而notify操作可以唤醒一个因调用了wait操作而处于阻塞状态中的线程,使其进去就绪状态。被重新唤醒的线程会视图重新获得临界区的控制权,也就是锁,并继续执行临界区内的代码。如果发出notify操作时没有处于阻塞状态中的线程,那么该命令会被忽略。

  wait()方法可以使调用该方法的线程释放共享资源的锁,然后从运行状态退出,进入等待队列,直到被再次唤醒。

  notify()方法可以随机唤醒等待队列中等待同一共享资源的“一个”线程,并使该线程退出等待队列,进入可运行状态,也就是notify()方法仅通知“一个”线程。

  notifyAll()方法可以使所有正在等待队列中等待统一共享资源的“全部”线程从等待状态退出,进入可运行状态。此时,优先级最高的那个线程最先执行,但也有可能是随机执行,因为这要取决于JVM虚拟机的实现。

Java多线程编程(三)线程间通信

Java多线程编程(三)线程间通信

  4.方法wait()锁释放与notify()锁不释放

  当wait()方法被执行后,锁被自动释放,但执行完notify()方法,锁却不自动释放。

  示例1:两个线程都对同一共享资源对象锁,其中一个线程执行完wait()后立刻释放锁,然后另一个线程得以执行。

package service;

public class Service {

    public void testMethod(Object lock) {
try {
synchronized (lock) {
System.out.println("begin wait()");
lock.wait();
System.out.println(" end wait()");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
package extthread;

import service.Service;

public class ThreadA extends Thread {

    private Object lock;

    public ThreadA(Object lock) {
super();
this.lock = lock;
} @Override
public void run() {
Service service = new Service();
service.testMethod(lock);
} }
package extthread;

import service.Service;

public class ThreadB extends Thread {

    private Object lock;

    public ThreadB(Object lock) {
super();
this.lock = lock;
} @Override
public void run() {
Service service = new Service();
service.testMethod(lock);
} }
package test;

import extthread.ThreadA;
import extthread.ThreadB; public class Test { public static void main(String[] args) { Object lock = new Object(); ThreadA a = new ThreadA(lock);
a.start(); ThreadB b = new ThreadB(lock);
b.start(); } }
begin wait()
begin wait()

  示例2:将wait()方法修改成sleep方法后,就成了同步的效果了。

package service;

public class Service {

    public void testMethod(Object lock) {
try {
synchronized (lock) {
System.out.println("begin wait()");
Thread.sleep(40000);
System.out.println(" end wait()");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
begin wait()
end wait()
begin wait()
end wait()

  示例3:从输出结果可以看出,notify都是成对打印的,这说明了必须执行完notify()方法所在的同步synchronized代码块后才释放锁。

package service;

public 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();
}
} }
package extthread;

import service.Service;

public class ThreadA extends Thread {
private Object lock; public ThreadA(Object lock) {
super();
this.lock = lock;
} @Override
public void run() {
Service service = new Service();
service.testMethod(lock);
} }
package extthread;

import service.Service;

public class NotifyThread extends Thread {
private Object lock; public NotifyThread(Object lock) {
super();
this.lock = lock;
} @Override
public void run() {
Service service = new Service();
service.synNotifyMethod(lock);
} }
package extthread;

import service.Service;

public class synNotifyMethodThread extends Thread {
private Object lock; public synNotifyMethodThread(Object lock) {
super();
this.lock = lock;
} @Override
public void run() {
Service service = new Service();
service.synNotifyMethod(lock);
} }
package test;

import extthread.NotifyThread;
import extthread.ThreadA;
import extthread.synNotifyMethodThread; public class Test { public static void main(String[] args) throws InterruptedException { Object lock = new Object(); ThreadA a = new ThreadA(lock);
a.start(); NotifyThread notifyThread = new NotifyThread(lock);
notifyThread.start(); synNotifyMethodThread c = new synNotifyMethodThread(lock);
c.start(); } }
begin wait()   ThreadName=Thread-0 time=1525508164635
begin notify() ThreadName=Thread-2 time=1525508164635
end notify() ThreadName=Thread-2 time=1525508169635
begin notify() ThreadName=Thread-1 time=1525508169635
end notify() ThreadName=Thread-1 time=1525508174635
end wait() ThreadName=Thread-0 time=1525508174635

  5.当interrupt方法遇到wait方法

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

package service;

public class Service {

    public void testMethod(Object lock) {
try {
synchronized (lock) {
System.out.println("begin wait()");
lock.wait();
System.out.println(" end wait()");
}
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("出现异常了,因为呈wait状态的线程被interrupt了!");
}
} }
package extthread;

import service.Service;

public class ThreadA extends Thread {

    private Object lock;

    public ThreadA(Object lock) {
super();
this.lock = lock;
} @Override
public void run() {
Service service = new Service();
service.testMethod(lock);
} }
package test;

import extthread.ThreadA;

public class Test {

    public static void main(String[] args) {

        try {
Object lock = new Object(); ThreadA a = new ThreadA(lock);
a.start(); Thread.sleep(5000); a.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
} } }
begin wait()
java.lang.InterruptedException
出现异常了,因为呈wait状态的线程被interrupt了!
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Unknown Source)
at service.Service.testMethod(Service.java:9)
at extthread.ThreadA.run(ThreadA.java:17)

  总结:

  (1)wait()方法执行完同步代码块就会释放对象的锁。

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

  (3)在执行同步代码块的过程中,执行了锁所属对象的wait(0方法,这个线程会释放对象锁,而此线程对象会进入线程等待池中,等待被唤醒。

  6.只通知一个线程

  示例1:调用notify()方法一次只随机通知一个线程进行唤醒。线程A、B、C都执行wait()方法,通知线程只执行一次notify()方法。从输出结果也可以看出,随机唤醒三个线程的任意一个。

package extthread;

import service.Service;

public class NotifyThread extends Thread {
private Object lock; public NotifyThread(Object lock) {
super();
this.lock = lock;
} @Override
public void run() {
synchronized (lock) {
lock.notify();
}
}
package extthread;

import service.Service;

public class ThreadA extends Thread {
private Object lock; public ThreadA(Object lock) {
super();
this.lock = lock;
} @Override
public void run() {
Service service = new Service();
service.testMethod(lock);
} }
package service;

public 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();
}
} }
package test;

import extthread.NotifyThread;
import extthread.ThreadA;
import extthread.ThreadB;
import extthread.ThreadC; public class Test { public static void main(String[] args) throws InterruptedException { Object lock = new Object(); ThreadA a = new ThreadA(lock);
a.start(); ThreadB b = new ThreadB(lock);
b.start(); ThreadC c = new ThreadC(lock);
c.start(); Thread.sleep(1000); NotifyThread notifyThread = new NotifyThread(lock);
notifyThread.start(); } }
begin wait() ThreadName=Thread-1
begin wait() ThreadName=Thread-2
begin wait() ThreadName=Thread-0
end wait() ThreadName=Thread-1

  示例2:修改示例1中的通知线程,多次调用notify()方法,会随机将等待wait状态的线程进行唤醒。

package extthread;

import service.Service;

public class NotifyThread extends Thread {
private Object lock; public NotifyThread(Object lock) {
super();
this.lock = lock;
} @Override
public void run() {
synchronized (lock) {
lock.notify();
lock.notify();
lock.notify();
lock.notify();
lock.notify();
lock.notify();
lock.notify();
lock.notify();
lock.notify();
}
} }
begin wait() ThreadName=Thread-0
begin wait() ThreadName=Thread-2
begin wait() ThreadName=Thread-1
end wait() ThreadName=Thread-0
end wait() ThreadName=Thread-1
end wait() ThreadName=Thread-2

  7.唤醒所有线程

  示例:修改6中的实例,将notify()方法修改成notifyAll()方法并只执行一次,就可以唤醒全部处于wait状态的线程。

package extthread;

import service.Service;

public class NotifyThread extends Thread {
private Object lock; public NotifyThread(Object lock) {
super();
this.lock = lock;
} @Override
public void run() {
synchronized (lock) {
lock.notifyAll(); }
} }
begin wait() ThreadName=Thread-0
begin wait() ThreadName=Thread-1
begin wait() ThreadName=Thread-2
end wait() ThreadName=Thread-2
end wait() ThreadName=Thread-1
end wait() ThreadName=Thread-0

  8.方法wait(long)的使用

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

  示例1:线程等待了5秒后,自动被唤醒,即退出wait状态。

package myrunnable;

public class MyRunnable {
static private Object lock = new Object(); static private Runnable runnable1 = new Runnable() {
@Override
public void run() {
try {
synchronized (lock) {
System.out.println("wait begin timer="+ System.currentTimeMillis());
lock.wait(5000);
System.out.println("wait end timer="+ System.currentTimeMillis());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}; static private Runnable runnable2 = new Runnable() {
@Override
public void run() {
synchronized (lock) {
System.out.println("notify begin timer="+ System.currentTimeMillis());
lock.notify();
System.out.println("notify end timer="+ System.currentTimeMillis());
}
}
}; public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(runnable1);
t1.start();
//Thread.sleep(3000);
//Thread t2 = new Thread(runnable2);
//t2.start();
} }
wait   begin timer=1525511220380
wait end timer=1525511225381

  示例2:也可以在未唤醒之前由其他线程唤醒。从结果可以看出,在3秒后由其他线程唤醒。

package myrunnable;

public class MyRunnable {
static private Object lock = new Object(); static private Runnable runnable1 = new Runnable() {
@Override
public void run() {
try {
synchronized (lock) {
System.out.println("wait begin timer="+ System.currentTimeMillis());
lock.wait(5000);
System.out.println("wait end timer="+ System.currentTimeMillis());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}; static private Runnable runnable2 = new Runnable() {
@Override
public void run() {
synchronized (lock) {
System.out.println("notify begin timer="+ System.currentTimeMillis());
lock.notify();
System.out.println("notify end timer="+ System.currentTimeMillis());
}
}
}; public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(runnable1);
t1.start();
Thread.sleep(3000);
Thread t2 = new Thread(runnable2);
t2.start();
} }
wait   begin timer=1525511382723
notify begin timer=1525511385724
notify end timer=1525511385724
wait end timer=1525511385724

  9.通知过早

  如果通知过早,就会打乱程序正常的运行逻辑。

  示例1:正常的执行顺序是先wait,然后等待100秒,然后通知,这样是正确的结果。

package test;

public class MyRun {

    private String lock = new String("");
private boolean isFirstRunB = false; private Runnable runnableA = new Runnable() {
@Override
public void run() {
try {
synchronized (lock) {
while (isFirstRunB == false) {
System.out.println("begin wait");
lock.wait();
System.out.println("end wait");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}; private Runnable runnableB = new Runnable() {
@Override
public void run() {
synchronized (lock) {
System.out.println("begin notify");
lock.notify();
System.out.println("end notify");
isFirstRunB = true; }
}
}; public static void main(String[] args) throws InterruptedException { MyRun run = new MyRun(); Thread a = new Thread(run.runnableA);
a.start(); Thread.sleep(100); Thread b = new Thread(run.runnableB);
b.start(); } }
begin wait
begin notify
end notify
end wait

  示例2:将线程B先执行,然后sleep100毫秒,然后执行线程A,会导致先通知的情况下,wait方法就没有必要执行了。

begin notify
end notify

  示例3:修改程序,将逻辑去掉,先A后B,可以得到正确的结果。

package test;

public class MyRun {

    private String lock = new String("");
private boolean isFirstRunB = false; private 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();
}
}
}; private Runnable runnableB = new Runnable() {
@Override
public void run() {
synchronized (lock) {
System.out.println("begin notify");
lock.notify();
System.out.println("end notify");
isFirstRunB = true; }
}
}; public static void main(String[] args) throws InterruptedException { MyRun run = new MyRun(); Thread a = new Thread(run.runnableA);
a.start(); Thread.sleep(100); Thread b = new Thread(run.runnableB);
b.start(); } }
begin wait
begin notify
end notify
end wait

  示例4:先B后A,方法wait永远不会被通知。

begin notify
end notify
begin wait

  10.等待wait的条件发生变化

  wait等待的条件发生了变化,也容易造成程序逻辑的混乱。

  示例1:出现异常的原因是,有两个实现删除remove()操作的线程,即两个减法线程,在main方法中,sleep(1000)之前,两个线程都执行了wait()方法,呈等待状态。当加法线程在1秒后被运行时,通知了所有呈wait状态的两个减法线程,然后两个减法线程就去争抢执行减法操作,那么第一个减法线程可以正确地删除list中索引为0的数据,但第二个减法线程则出现索引溢出的异常,因为list中仅仅添加了一个数据,也只能删除一个数据,所以没有第二个数据可供删除。

package entity;

import java.util.ArrayList;
import java.util.List; public class ValueObject { public static List<String> list = new ArrayList<String>(); }
package entity;

//加法
public class Add { private String lock; public Add(String lock) {
super();
this.lock = lock;
} public void add() {
synchronized (lock) {
ValueObject.list.add("anyString");
lock.notifyAll();
}
} }
package entity;

//减法
public class Subtract { private String lock; public Subtract(String lock) {
super();
this.lock = lock;
} public void subtract() {
try {
synchronized (lock) {
if (ValueObject.list.size() == 0) {
System.out.println("wait begin ThreadName="+ Thread.currentThread().getName());
lock.wait();
System.out.println("wait end ThreadName="+ Thread.currentThread().getName());
}
ValueObject.list.remove(0);
System.out.println("list size=" + ValueObject.list.size());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
package extthread;

import entity.Add;

public class ThreadAdd extends Thread {

    private Add p;

    public ThreadAdd(Add p) {
super();
this.p = p;
} @Override
public void run() {
p.add();
} }
package extthread;

import entity.Subtract;

public class ThreadSubtract extends Thread {

    private Subtract r;

    public ThreadSubtract(Subtract r) {
super();
this.r = r;
} @Override
public void run() {
r.subtract();
} }
package test;

import entity.Add;
import entity.Subtract;
import extthread.ThreadAdd;
import extthread.ThreadSubtract; public class Run { public static void main(String[] args) throws InterruptedException { String lock = new String(""); Add add = new Add(lock);
Subtract subtract = new Subtract(lock); ThreadSubtract subtract1Thread = new ThreadSubtract(subtract);
subtract1Thread.setName("subtract1Thread");
subtract1Thread.start(); ThreadSubtract subtract2Thread = new ThreadSubtract(subtract);
subtract2Thread.setName("subtract2Thread");
subtract2Thread.start(); Thread.sleep(1000); ThreadAdd addThread = new ThreadAdd(add);
addThread.setName("addThread");
addThread.start(); } }
wait begin ThreadName=subtract1Thread
wait begin ThreadName=subtract2Thread
wait end ThreadName=subtract2Thread
list size=0
wait end ThreadName=subtract1Thread
Exception in thread "subtract1Thread" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.remove(Unknown Source)
at entity.Subtract.subtract(Subtract.java:21)
at extthread.ThreadSubtract.run(ThreadSubtract.java:16)

  示例2:将减法线程中的if语句改成while语句,这样就可以解决异常的情况。

package entity;

//减法
public class Subtract { private String lock; public Subtract(String lock) {
super();
this.lock = lock;
} public void subtract() {
try {
synchronized (lock) {
while (ValueObject.list.size() == 0) {
System.out.println("wait begin ThreadName="+ Thread.currentThread().getName());
lock.wait();
System.out.println("wait end ThreadName="+ Thread.currentThread().getName());
}
ValueObject.list.remove(0);
System.out.println("list size=" + ValueObject.list.size());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
wait begin ThreadName=subtract2Thread
wait begin ThreadName=subtract1Thread
wait end ThreadName=subtract1Thread
list size=0
wait end ThreadName=subtract2Thread
wait begin ThreadName=subtract2Thread

  11.生产者/消费者模式实现

  (1)一生产与一消费:操作值

  示例:set和get交替运行,两个线程中的if语句决定了第一个执行的一定是生产者的set过程,然后然后两个线程互相交替set和get。

package entity;

public class ValueObject {

    public static String value = "";

}
package entity;

//生产者
public class P { private String lock; public P(String lock) {
super();
this.lock = lock;
} public void setValue() {
try {
synchronized (lock) {
if (!ValueObject.value.equals("")) {
lock.wait();
}
String value = System.currentTimeMillis() + "_"+ System.nanoTime();
System.out.println("set的值是" + value);
ValueObject.value = value;
lock.notify();
} } catch (InterruptedException e) {
e.printStackTrace();
}
} }
package entity;

//消费者
public class C { private String lock; public C(String lock) {
super();
this.lock = lock;
} public void getValue() {
try {
synchronized (lock) {
if (ValueObject.value.equals("")) {
lock.wait();
}
System.out.println("get的值是" + ValueObject.value);
ValueObject.value = "";
lock.notify();
} } catch (InterruptedException e) {
e.printStackTrace();
}
} }
package extthread;

import entity.C;

public class ThreadC extends Thread {

    private C r;

    public ThreadC(C r) {
super();
this.r = r;
} @Override
public void run() {
while (true) {
r.getValue();
}
} }
package extthread;

import entity.P;

public class ThreadP extends Thread {

    private P p;

    public ThreadP(P p) {
super();
this.p = p;
} @Override
public void run() {
while (true) {
p.setValue();
}
} }
package test;

import entity.P;
import entity.C;
import extthread.ThreadP;
import extthread.ThreadC; public class Run { public static void main(String[] args) { String lock = new String("");
P p = new P(lock);
C r = new C(lock); ThreadP pThread = new ThreadP(p);
ThreadC rThread = new ThreadC(r); pThread.start();
rThread.start();
} }
set的值是1525522701519_86515436524665
get的值是1525522701519_86515436524665
set的值是1525522701519_86515436548871
get的值是1525522701519_86515436548871
set的值是1525522701519_86515436566512
get的值是1525522701519_86515436566512
set的值是1525522701519_86515436584153
get的值是1525522701519_86515436584153
set的值是1525522701519_86515436601383
get的值是1525522701519_86515436601383
set的值是1525522701519_86515436619435
get的值是1525522701519_86515436619435
set的值是1525522701519_86515436643640
get的值是1525522701519_86515436643640
set的值是1525522701519_86515436661691
get的值是1525522701519_86515436661691
set的值是1525522701519_86515436679742
get的值是1525522701519_86515436679742
...

  (2)多生产与多消费:操作值-假死

  “假死”的现象其实就是线程进入wait等待状态。如果全部线程都进入wait状态,那程序就不再执行任何业务功能了,整个项目呈停止状态。

  示例:两个生产者线程和两个消费者线程,下面按每一行详细分析执行过程。假死的主要原因就是有可能连续唤醒同类。

package entity;

public class ValueObject {

    public static String value = "";

}
package entity;

//生产者
public class P { private String lock; public P(String lock) {
super();
this.lock = lock;
} public void setValue() {
try {
synchronized (lock) {
while (!ValueObject.value.equals("")) {
System.out.println("生产者 "+ Thread.currentThread().getName() + " WAITING了★");
lock.wait();
}
System.out.println("生产者 " + Thread.currentThread().getName()+ " RUNNABLE了");
String value = System.currentTimeMillis() + "_"+ System.nanoTime();
ValueObject.value = value;
lock.notify();
} } catch (InterruptedException e) {
e.printStackTrace();
}
} }
package entity;

//消费者
public class C { private String lock; public C(String lock) {
super();
this.lock = lock;
} public void getValue() {
try {
synchronized (lock) {
while (ValueObject.value.equals("")) {
System.out.println("消费者 "+ Thread.currentThread().getName() + " WAITING了☆");
lock.wait();
}
System.out.println("消费者 " + Thread.currentThread().getName()+ " RUNNABLE了");
ValueObject.value = "";
lock.notify();
} } catch (InterruptedException e) {
e.printStackTrace();
}
} }
package extthread;

import entity.P;

public class ThreadP extends Thread {

    private P p;

    public ThreadP(P p) {
super();
this.p = p;
} @Override
public void run() {
while (true) {
p.setValue();
}
} }
package extthread;

import entity.C;

public class ThreadC extends Thread {

    private C r;

    public ThreadC(C r) {
super();
this.r = r;
} @Override
public void run() {
while (true) {
r.getValue();
}
} }
package test;

import entity.P;
import entity.C;
import extthread.ThreadP;
import extthread.ThreadC; public class Run { public static void main(String[] args) throws InterruptedException { String lock = new String("");
P p = new P(lock);
C r = new C(lock); ThreadP[] pThread = new ThreadP[2];
ThreadC[] rThread = new ThreadC[2]; for (int i = 0; i < 2; i++) {
pThread[i] = new ThreadP(p);
pThread[i].setName("生产者" + (i + 1)); rThread[i] = new ThreadC(r);
rThread[i].setName("消费者" + (i + 1)); pThread[i].start();
rThread[i].start();
} Thread.sleep(5000);
Thread[] threadArray = new Thread[Thread.currentThread().getThreadGroup().activeCount()];
Thread.currentThread().getThreadGroup().enumerate(threadArray); for (int i = 0; i < threadArray.length; i++) {
System.out.println(threadArray[i].getName() + " "+ threadArray[i].getState());
}
} }
生产者 生产者1 RUNNABLE了
生产者 生产者1 WAITING了★
生产者 生产者2 WAITING了★
消费者 消费者2 RUNNABLE了
消费者 消费者2 WAITING了☆
消费者 消费者1 WAITING了☆
生产者 生产者1 RUNNABLE了
生产者 生产者1 WAITING了★
生产者 生产者2 WAITING了★
main RUNNABLE
生产者1 WAITING
消费者1 WAITING
生产者2 WAITING
消费者2 WAITING

  输出结果分析(结果不唯一,有可能出现其他情况,但最后的结果都是四个线程都进入wait状态。):

  ①生产者1进行生产,while判断语句不通过,执行生产语句,执行赋值操作后,发出通知,并释放锁,准备进入下一次的while循环。

  ②生产者1进行了下一次whlie循环,whlie判断语句通过,进入wait等待状态。

  ③生产者2被启动,生产者2whlie判断语句通过,也进入wait等待状态。

  ④消费者2被启动,判断语句不通过,进入消费状态,并发出通知唤醒第七行中的生产者1,运行结束后释放锁,等待消费者2进行下一次循环。

  ⑤消费者2进行下一次while循环,判断语句通过,进入等待状态。

  ⑥消费者1被启动,判断语句通过,也进入等待状态。

  ⑦生产者1被④中的通知唤醒,判断语句不通过,执行生产语句,然后发出通知,准备进入下一次的whlie循环。

  ⑧生产者1进入下一次whlie循环,判断语句通过,进入wait等待状态。

  ⑨由于⑦发出了通知,唤醒了生产者2,生产者2判断语句通过,也进入wait等待状态。

  (3)多生产与多消费:操作值

  示例:(2)中的代码,将生产者与消费者执行方法中的notify()修改成notifyAll()方法, 这样就可以解决问题了,程序就可以一直运行下去。原理是,不只是通知同类线程,也包括异类线程,这样就不会出现假死的状态了,程序就会一直运行下去。

package entity;

//生产者
public class P { private String lock; public P(String lock) {
super();
this.lock = lock;
} public void setValue() {
try {
synchronized (lock) {
while (!ValueObject.value.equals("")) {
System.out.println("生产者 "+ Thread.currentThread().getName() + " WAITING了★");
lock.wait();
}
System.out.println("生产者 " + Thread.currentThread().getName()+ " RUNNABLE了");
String value = System.currentTimeMillis() + "_"+ System.nanoTime();
ValueObject.value = value;
lock.notifyAll();
} } catch (InterruptedException e) {
e.printStackTrace();
}
} }
package entity;

//消费者
public class C { private String lock; public C(String lock) {
super();
this.lock = lock;
} public void getValue() {
try {
synchronized (lock) {
while (ValueObject.value.equals("")) {
System.out.println("消费者 "+ Thread.currentThread().getName() + " WAITING了☆");
lock.wait();
}
System.out.println("消费者 " + Thread.currentThread().getName()+ " RUNNABLE了");
ValueObject.value = "";
lock.notifyAll();
} } catch (InterruptedException e) {
e.printStackTrace();
}
} }

  (4)一生产与一消费:操作栈

  示例:生产者向堆栈List对象中放入数据,消费者从List堆栈中取出数据。List最大容量是1,且只有一个生产者和一个消费者。程序运行结果是size()不会大于1,值在0和1之间进行交替,也就是生产和消费这两个过程在交替执行。

package entity;

import java.util.ArrayList;
import java.util.List; public class MyStack {
private List<String> list = new ArrayList<String>(); synchronized public void push() {
try {
if (list.size() == 1) {
this.wait();
}
list.add("anyString=" + Math.random());
this.notify();
System.out.println("push=" + list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
} synchronized public String pop() {
String returnValue = "";
try {
if (list.size() == 0) {
System.out.println("pop操作中的:"+ Thread.currentThread().getName() + " 线程呈wait状态");
this.wait();
}
returnValue = "" + list.get(0);
list.remove(0);
this.notify();
System.out.println("pop=" + list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
return returnValue;
}
}
package service;

import entity.MyStack;

public class C {

    private MyStack myStack;

    public C(MyStack myStack) {
super();
this.myStack = myStack;
} public void popService() {
System.out.println("pop=" + myStack.pop());
}
}
package service;

import entity.MyStack;

public class P {

    private MyStack myStack;

    public P(MyStack myStack) {
super();
this.myStack = myStack;
} public void pushService() {
myStack.push();
}
}
package extthread;

import service.C;

public class C_Thread extends Thread {

    private C r;

    public C_Thread(C r) {
super();
this.r = r;
} @Override
public void run() {
while (true) {
r.popService();
}
} }
package extthread;

import service.P;

public class P_Thread extends Thread {

    private P p;

    public P_Thread(P p) {
super();
this.p = p;
} @Override
public void run() {
while (true) {
p.pushService();
}
} }
package test.run;

import service.P;
import service.C;
import entity.MyStack;
import extthread.P_Thread;
import extthread.C_Thread; public class Run {
public static void main(String[] args) {
MyStack myStack = new MyStack(); P p = new P(myStack);
C r = new C(myStack); P_Thread pThread = new P_Thread(p);
C_Thread rThread = new C_Thread(r);
pThread.start();
rThread.start();
} }
push=1
pop=0
pop=anyString=0.3254503931098508
push=1
pop=0
pop=anyString=0.6957780954007395
push=1
pop=0
pop=anyString=0.5752314740754261
push=1
pop=0
pop=anyString=0.6358907873485814
push=1
pop=0
pop=anyString=0.5491334774745474
push=1
pop=0
pop=anyString=0.7318824495167014
push=1
pop=0
pop=anyString=0.5984936669842421
push=1
pop=0
pop=anyString=0.47994410023033296
push=1
pop=0
pop=anyString=0.15752443606208588
push=1
pop=0
pop=anyString=0.02593849380725266
push=1
pop=0
pop=anyString=0.6580876878111466
push=1
pop=0
pop=anyString=0.04516506982998558
push=1
pop=0
pop=anyString=0.718448881542528
push=1
pop=0
pop=anyString=0.37108334401362963
push=1
pop=0
pop=anyString=0.6501388479925284
push=1
pop=0
pop=anyString=0.47586404781477243
push=1
pop=0
pop=anyString=0.9295344765233564
push=1
pop=0
pop=anyString=0.5197464329430267
push=1
pop=0
pop=anyString=0.8813580448635558
push=1
pop=0
pop=anyString=0.2578693811523306
push=1
pop=0
pop=anyString=0.37409514156698975
push=1
pop=0
pop=anyString=0.3031788471366039
push=1
pop=0
pop=anyString=0.8020652463477314
push=1
pop=0
...

  (5)一生产与多消费:操作栈:解决wait条件改变与假死

  示例1:一个生产者向堆栈List对象中放入数据,而多个消费者从List堆栈中取出数据,List最大容量还是1。修改(4)中的Run类,一个生产者和五个消费者的情况。MyStack.java类中使用if语句作为条件判断。因为条件发生改变时并没有得到及时的相应,所以多个呈wait状态的线程被唤醒, 继而执行list.remove(0)代码而出现异常。解决这个的办法是,将if改成whlie即可。

package test.run;

import service.P;
import service.C;
import entity.MyStack;
import extthread.P_Thread;
import extthread.C_Thread; public class Run {
public static void main(String[] args) {
MyStack myStack = new MyStack(); P p = new P(myStack);
C r1 = new C(myStack);
C r2 = new C(myStack);
C r3 = new C(myStack);
C r4 = new C(myStack);
C r5 = new C(myStack); P_Thread pThread = new P_Thread(p);
C_Thread rThread1 = new C_Thread(r1);
C_Thread rThread2 = new C_Thread(r2);
C_Thread rThread3 = new C_Thread(r3);
C_Thread rThread4 = new C_Thread(r4);
C_Thread rThread5 = new C_Thread(r5);
pThread.start();
rThread1.start();
rThread2.start();
rThread3.start();
rThread4.start();
rThread5.start();
} }
push=1
pop=anyString=0.1156301194548911
pop=0
pop=anyString=0.1156301194548911
pop操作中的:Thread-1 线程呈wait状态
pop操作中的:Thread-4 线程呈wait状态
pop操作中的:Thread-3 线程呈wait状态
pop操作中的:Thread-2 线程呈wait状态
pop操作中的:Thread-5 线程呈wait状态
push=1
pop=anyString=0.2969600462095914
pop=0
pop=anyString=0.2969600462095914
pop操作中的:Thread-1 线程呈wait状态
Exception in thread "Thread-4" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at entity.MyStack.pop(MyStack.java:32)
at service.C.popService(C.java:15)
at extthread.C_Thread.run(C_Thread.java:17)

  示例2:为了消除示例1中的异常, 将if语句改成whlie语句,这样做确实消除了异常,但是却出现了“假死”的情况。解决的方法当然还是将notify()方法改成notifyAll()方法。

push=1
pop=0
pop=anyString=0.8374332213169516
pop操作中的:Thread-5 线程呈wait状态
pop操作中的:Thread-3 线程呈wait状态
pop操作中的:Thread-2 线程呈wait状态
pop操作中的:Thread-1 线程呈wait状态
pop操作中的:Thread-4 线程呈wait状态
push=1
pop=0
pop=anyString=0.8740566480464856
pop操作中的:Thread-3 线程呈wait状态
pop操作中的:Thread-5 线程呈wait状态

  示例3:将notify()方法改成notifyAll()方法可以解决“假死”的问题,具体输出如下,有兴趣的可以分析一下执行过程。

pop=anyString=0.5839911873460317
pop操作中的:Thread-4 线程呈wait状态
pop操作中的:Thread-2 线程呈wait状态
pop操作中的:Thread-5 线程呈wait状态
pop操作中的:Thread-1 线程呈wait状态
push=1
pop=0
pop=anyString=0.7258314594848488
push=1
pop=0
pop=anyString=0.2812645500310439
pop操作中的:Thread-5 线程呈wait状态
pop操作中的:Thread-2 线程呈wait状态
pop操作中的:Thread-4 线程呈wait状态
pop操作中的:Thread-1 线程呈wait状态
push=1
pop=0
pop=anyString=0.42098357833064437
push=1
pop=0
pop=anyString=0.6705247690886362
pop操作中的:Thread-4 线程呈wait状态
pop操作中的:Thread-2 线程呈wait状态
pop操作中的:Thread-5 线程呈wait状态
pop操作中的:Thread-1 线程呈wait状态
push=1
pop=0
pop=anyString=0.5187216316233966
push=1
pop=0
pop=anyString=0.5984864285943388
pop操作中的:Thread-5 线程呈wait状态
pop操作中的:Thread-2 线程呈wait状态
pop操作中的:Thread-4 线程呈wait状态
pop操作中的:Thread-1 线程呈wait状态
push=1
pop=0
pop=anyString=0.8992584810146089
push=1
pop=0
pop=anyString=0.8962891515250642
pop操作中的:Thread-4 线程呈wait状态
pop操作中的:Thread-2 线程呈wait状态
pop操作中的:Thread-5 线程呈wait状态
pop操作中的:Thread-1 线程呈wait状态
push=1
pop=0
pop=anyString=0.9142789789676089
push=1
pop=0
pop=anyString=0.5880907722890949
pop操作中的:Thread-5 线程呈wait状态
pop操作中的:Thread-2 线程呈wait状态
pop操作中的:Thread-4 线程呈wait状态
pop操作中的:Thread-1 线程呈wait状态

  (6)多生产与一消费:操作栈

  示例:在(5)的示例3的基础上修改Run.java,使其有多个生产者和一个消费者,从输出结果可以看出,push和pop值确实在0和1交替运行,但是会有线程wait状态的输出。

package test.run;

import service.C;
import service.P;
import entity.MyStack;
import extthread.C_Thread;
import extthread.P_Thread; public class Run {
public static void main(String[] args) throws InterruptedException {
MyStack myStack = new MyStack(); P p1 = new P(myStack);
P p2 = new P(myStack);
P p3 = new P(myStack);
P p4 = new P(myStack);
P p5 = new P(myStack);
P p6 = new P(myStack); P_Thread pThread1 = new P_Thread(p1);
P_Thread pThread2 = new P_Thread(p2);
P_Thread pThread3 = new P_Thread(p3);
P_Thread pThread4 = new P_Thread(p4);
P_Thread pThread5 = new P_Thread(p5);
P_Thread pThread6 = new P_Thread(p6);
pThread1.start();
pThread2.start();
pThread3.start();
pThread4.start();
pThread5.start();
pThread6.start(); C c1 = new C(myStack);
C_Thread cThread = new C_Thread(c1);
cThread.start(); } }
push=1
pop=0
pop=anyString=0.014834103871098847
push=1
pop=0
pop=anyString=0.6440453638062643
push=1
pop=0
pop=anyString=0.6046791928187536
push=1
pop=0
pop=anyString=0.6256159865535258
push=1
pop=0
pop=anyString=0.612883885725567
push=1
pop=0
pop=anyString=0.19664275758307848
push=1
pop=0
pop=anyString=0.3987413765108909
push=1
pop=0
pop=anyString=0.4436402093649049
push=1
pop=0
pop=anyString=0.06059233311382217
push=1
pop=0
pop=anyString=0.9833696404681963
push=1
pop=0
pop=anyString=0.1979360819377557
push=1
pop=0
pop=anyString=0.5182234836585098
push=1
pop=0
pop=anyString=0.586815755882819
push=1
pop=0
pop=anyString=0.2359007847065253
pop操作中的:Thread-6 线程呈wait状态
push=1
pop=0
pop=anyString=0.9692705021437371
pop操作中的:Thread-6 线程呈wait状态
push=1
pop=0
pop=anyString=0.8059112079970976
...

  (7)多生产与多消费:操作栈

  示例:修改Run.java使得有多个生产者和多个消费者,从输出结果可以看出,也是在0和1之间交替,list对象的size()并没有超过1。

package test.run;

import service.C;
import service.P;
import entity.MyStack;
import extthread.C_Thread;
import extthread.P_Thread; public class Run {
public static void main(String[] args) throws InterruptedException {
MyStack myStack = new MyStack(); P p1 = new P(myStack);
P p2 = new P(myStack);
P p3 = new P(myStack);
P p4 = new P(myStack);
P p5 = new P(myStack);
P p6 = new P(myStack); P_Thread pThread1 = new P_Thread(p1);
P_Thread pThread2 = new P_Thread(p2);
P_Thread pThread3 = new P_Thread(p3);
P_Thread pThread4 = new P_Thread(p4);
P_Thread pThread5 = new P_Thread(p5);
P_Thread pThread6 = new P_Thread(p6);
pThread1.start();
pThread2.start();
pThread3.start();
pThread4.start();
pThread5.start();
pThread6.start(); C r1 = new C(myStack);
C r2 = new C(myStack);
C r3 = new C(myStack);
C r4 = new C(myStack);
C r5 = new C(myStack);
C r6 = new C(myStack);
C r7 = new C(myStack);
C r8 = new C(myStack); C_Thread cThread1 = new C_Thread(r1);
C_Thread cThread2 = new C_Thread(r2);
C_Thread cThread3 = new C_Thread(r3);
C_Thread cThread4 = new C_Thread(r4);
C_Thread cThread5 = new C_Thread(r5);
C_Thread cThread6 = new C_Thread(r6);
C_Thread cThread7 = new C_Thread(r7);
C_Thread cThread8 = new C_Thread(r8); cThread1.start();
cThread2.start();
cThread3.start();
cThread4.start();
cThread5.start();
cThread6.start();
cThread7.start();
cThread8.start(); } }
push=1
pop=0
pop=anyString=0.4902132952539602
pop操作中的:Thread-9 线程呈wait状态
pop操作中的:Thread-12 线程呈wait状态
pop操作中的:Thread-8 线程呈wait状态
push=1
pop=0
pop=anyString=0.27018913089117513
pop操作中的:Thread-12 线程呈wait状态
pop操作中的:Thread-9 线程呈wait状态
push=1
pop=0
pop=anyString=0.5581725821570959
pop操作中的:Thread-11 线程呈wait状态
pop操作中的:Thread-13 线程呈wait状态
pop操作中的:Thread-7 线程呈wait状态
pop操作中的:Thread-10 线程呈wait状态
pop操作中的:Thread-6 线程呈wait状态
push=1
pop=0
pop=anyString=0.753402968862627
pop操作中的:Thread-6 线程呈wait状态
pop操作中的:Thread-10 线程呈wait状态
pop操作中的:Thread-7 线程呈wait状态
pop操作中的:Thread-13 线程呈wait状态
pop操作中的:Thread-11 线程呈wait状态
push=1
pop=0
pop=anyString=0.4822940142360146
pop操作中的:Thread-9 线程呈wait状态
pop操作中的:Thread-12 线程呈wait状态
pop操作中的:Thread-8 线程呈wait状态
...

  12.通过管道进行线程间通信:字节流

  在Java语言中提供了各种各样的输入/输出流Stream,使我们能够很方便地对数据进行操作,其中管道流pipeStream是一种特殊的流,用于在不同线程间直接传送数据。一个线程发送数据到输出管道,另一个线程从输入管道中读数据。通过使用管道,实现不同线程间的通信,而无需借助于类似临时文件之类的东西。

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

  (1)PipeInputStream和PipeOutputStream

  (2)PipeReader和PipedWriter

  示例:使用PipeInputStream和PipeOutputStream进行线程通过管道流传输字节流。Run类中main方法中的outputStream.connect(inputStream);是使两个Stream之间产生通信链接,这样才可以将数据进行输出与输入。由于Read线程启动2秒后Write线程才启动,由于没有数据被写入,所以线程阻塞在int readLength = input.read(byteArray);代码中,直到有数据被写入,才继续向下运行。

package extthread;

import java.io.PipedOutputStream;

import service.WriteData;

public class ThreadWrite extends Thread {

    private WriteData write;
private PipedOutputStream out; public ThreadWrite(WriteData write, PipedOutputStream out) {
super();
this.write = write;
this.out = out;
} @Override
public void run() {
write.writeMethod(out);
} }
package extthread;

import java.io.PipedInputStream;

import service.ReadData;

public class ThreadRead extends Thread {

    private ReadData read;
private PipedInputStream input; public ThreadRead(ReadData read, PipedInputStream input) {
super();
this.read = read;
this.input = input;
} @Override
public void run() {
read.readMethod(input);
}
}
package service;

import java.io.IOException;
import java.io.PipedInputStream; public class ReadData { 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();
}
}
}
package service;

import java.io.IOException;
import java.io.PipedOutputStream; public class WriteData { public void writeMethod(PipedOutputStream out) {
try {
System.out.println("write :");
for (int i = 0; i < 300; i++) {
String outData = "" + (i + 1);
out.write(outData.getBytes());
System.out.print(outData);
}
System.out.println();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package test;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream; import service.ReadData;
import service.WriteData;
import extthread.ThreadRead;
import extthread.ThreadWrite; 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();
} } }
read  :
write :
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182...
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182...

  13.通过管道进行线程间通信:字符流

  示例:使用PipeReader和PipedWriter在管道中传递字符流,原理和之前传递字节流一样,只不过修改成了 String outData = "" + (i + 1); out.write(outData);代码。

package service;

import java.io.IOException;
import java.io.PipedWriter; public class WriteData { public void writeMethod(PipedWriter out) {
try {
System.out.println("write :");
for (int i = 0; i < 100; i++) {
String outData = "" + (i + 1);
out.write(outData);
System.out.print(outData);
}
System.out.println();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package service;

import java.io.IOException;
import java.io.PipedReader; public 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();
}
}
}
read  :
write :
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950...
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950...

  14.实战:等待/通知之交叉备份

  示例:创建20个线程,其中10个线程是将数据备份到A数据库,另外10个线程将数据备份到B数据库中,并且备份A数据库和B数据库是交叉进行的。打印的效果是交替运行的,这是因为修改volatile private boolean prevIsA = false;的值来实现线程A和线程B交替备份的效果的。

package service;

public class DBTools {

    volatile private boolean prevIsA = false;

    synchronized public void backupA() {
try {
while (prevIsA == true) {
wait();
}
for (int i = 0; i < 5; i++) {
System.out.println("AAAAA");
}
prevIsA = true;
notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
} synchronized public void backupB() {
try {
while (prevIsA == false) {
wait();
}
for (int i = 0; i < 5; i++) {
System.out.println("BBBBB");
}
prevIsA = false;
notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package extthread;

import service.DBTools;

public class BackupA extends Thread {

    private DBTools dbtools;

    public BackupA(DBTools dbtools) {
super();
this.dbtools = dbtools;
} @Override
public void run() {
dbtools.backupA();
} }
package extthread;

import service.DBTools;

public class BackupB extends Thread {

    private DBTools dbtools;

    public BackupB(DBTools dbtools) {
super();
this.dbtools = dbtools;
} @Override
public void run() {
dbtools.backupB();
} }
package test.run;

import service.DBTools;
import extthread.BackupA;
import extthread.BackupB; public class Run { public static void main(String[] args) {
DBTools dbtools = new DBTools();
for (int i = 0; i < 20; i++) {
BackupB output = new BackupB(dbtools);
output.start();
BackupA input = new BackupA(dbtools);
input.start();
}
} }
AAAAA
AAAAA
AAAAA
AAAAA
AAAAA
BBBBB
BBBBB
BBBBB
BBBBB
BBBBB
AAAAA
AAAAA
AAAAA
AAAAA
AAAAA
BBBBB
BBBBB
BBBBB
BBBBB
BBBBB
...

  二、方法join的使用

  在很多情况下,主线程创建并启动子线程,如果子线程中要进行大量的耗时运算,主线程往往将早于子线程结束之前结束。这时,如果主线程想等待子线程执行完之后再结束,比如子线程处理一个数据,主线程要取得这个数据中的值,就要用到join()方法了。join()方法的作用是等待线程对象的销毁。

  1.学习方法join前的铺垫

  示例:main方法中的sleep()中的值不能确定。

package extthread;

public class MyThread extends Thread {

    @Override
public void run() {
try {
int secondValue = (int) (Math.random() * 10000);
System.out.println(secondValue);
Thread.sleep(secondValue);
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
package test;

import extthread.MyThread;

public class Test {

    public static void main(String[] args) {

        MyThread threadTest = new MyThread();
threadTest.start(); // Thread.sleep(?)
System.out.println("要想threadTest线程执行完Thread.sleep(secondValue);之后再执行,"
+ "是无法确定sleep的值的");
} }
要想threadTest线程执行完Thread.sleep(secondValue);之后再执行,是无法确定sleep的值的
5433

  2.用join()方法来解决

  示例:修改1中示例的main方法,加入join()方法后,确实可以做到,主线程等待子线程执行完之后再执行主线程的代码。

  方法join()的作用是使所属的线程对象x(子线程threadTest)正常执行run()方法中的任务,而使当前线程z(主线程main)进行无限期的阻塞,等待线程x销毁后再继续执行z后面的代码。

  方法join()具有使线程派对运行的作用,有些类似同步的运行效果。join与synchronized的区别是:join在内部使用wait()方法进行等待,而synchronized关键字使用的是“对象监视器”原理做同步。

package test;

import extthread.MyThread;

public class Test {

    public static void main(String[] args) {
try {
MyThread threadTest = new MyThread();
threadTest.start();
threadTest.join();
System.out.println("main线程中想要等待子线程执行完之后执行的东西");
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
4758
main线程中想要等待子线程执行完之后执行的东西

  3.方法join与异常

  示例:在join过程中,如果当前线程对象被中断,则当前线程出现异常。线程B启动线程A并且加入join()方法,B启动500毫秒后,线程C启动将线程B中断,然后线程B出现异常。说明了方法join()和interrupt()方法如果彼此遇到,则会出现异常。但进程按钮还呈“红色”,这是因为线程A还在继续运行,线程A并未出现异常,还是正常的执行状态。

package extthread;

public class ThreadA extends Thread {
@Override
public void run() {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
Math.random();
}
}
}
package extthread;

public class ThreadB extends Thread {

    @Override
public void run() {
try {
ThreadA a = new ThreadA();
a.start();
a.join(); System.out.println("线程B的run方法的最后一行!");
} catch (InterruptedException e) {
System.out.println("线程B的catch处!");
e.printStackTrace();
}
} }
package extthread;

public class ThreadC extends Thread {

    private ThreadB threadB;

    public ThreadC(ThreadB threadB) {
super();
this.threadB = threadB;
} @Override
public void run() {
threadB.interrupt();
} }
package test.run;

import extthread.ThreadB;
import extthread.ThreadC; public class Run { public static void main(String[] args) { try {
ThreadB b = new ThreadB();
b.start(); Thread.sleep(500); ThreadC c = new ThreadC(b);
c.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
线程B的catch处!
java.lang.InterruptedException
at java.lang.Object.wait(Native Method)
at java.lang.Thread.join(Unknown Source)
at java.lang.Thread.join(Unknown Source)
at extthread.ThreadB.run(ThreadB.java:10)

  4.方法join(long)的使用

  示例1:方法join(long)中的参数是设定等待的时间。main线程等待子线程2秒后才是执行自己的线程。

package extthread;

public class MyThread extends Thread {

    @Override
public void run() {
try {
System.out.println("begin Timer=" + System.currentTimeMillis());
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
package test;

import extthread.MyThread;

public class Test {

    public static void main(String[] args) {
try {
MyThread threadTest = new MyThread();
threadTest.start(); threadTest.join(2000); System.out.println(" end timer=" + System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
begin Timer=1525596937162
end timer=1525596939162

  示例2:将main方法中的代码改成sleep(2000),运行的效果还是等待了2秒。看起来似乎没有什么区别,但是其实是对同步的处理不同。

package test;

import extthread.MyThread;

public class Test {

    public static void main(String[] args) {
try {
MyThread threadTest = new MyThread();
threadTest.start(); //threadTest.join(2000);
Thread.sleep(2000); System.out.println(" end timer=" + System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
begin Timer=1525597086235
end timer=1525597088236

  5.方法join(long)与sleep(long)的区别

  方法join(long)的功能在内部是使用了wait(long)方法来实现的,所以方法join(long)具有释放锁的特点。

  从方法join(long)的源码

    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;
}
}
}

  可以看出,当执行了wait(long)方法后,当前线程的锁被释放,那么其他线程就可以调用此线程中的同步方法了。

  而从sleep(long)方法的源码可以看出,sleep(long)方法并不释放锁。

    public static void sleep(long millis, int nanos)
throws InterruptedException {
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
} if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
} if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
millis++;
} sleep(millis);
}

  示例:线程A启动,然后线程B被线程A启动,在线程A启动的1000毫秒后线程C启动,线程C执行线程B的同步方法bService中的打印语句。由于线程A使用Thread.sleep(6000);一直持有线程B对象的锁达到6秒,然后线程C只有在线程A时间达到6秒后释放线程B对象锁时,才可以调用线程B中的同步方法。证明了在Thread.sleep(6000);过程中不释放锁。

package extthread;

public class ThreadB extends Thread {

    @Override
public 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());
} }
package extthread;

public class ThreadC extends Thread {

    private ThreadB threadB;

    public ThreadC(ThreadB threadB) {
super();
this.threadB = threadB;
} @Override
public void run() {
threadB.bService();
} }
package extthread;

public class ThreadA extends Thread {

    private ThreadB b;

    public ThreadA(ThreadB b) {
super();
this.b = b;
} @Override
public void run() {
try {
synchronized (b) {
b.start();
Thread.sleep(6000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package test.run;

import extthread.ThreadA;
import extthread.ThreadB;
import extthread.ThreadC; public class Run { public static void main(String[] args) { try {
ThreadB b = new ThreadB(); ThreadA a = new ThreadA(b);
a.start(); Thread.sleep(1000); ThreadC c = new ThreadC(b);
c.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
} }

  示例2:修改线程A类,改成join()方法,从输出结果可以看出,线程A释放了线程B的锁,所以线程C可以调用线程B中的同步方法,证明了join(long)方法具有释放锁的特点。

package extthread;

public class ThreadA extends Thread {

    private ThreadB b;

    public ThreadA(ThreadB b) {
super();
this.b = b;
} @Override
public void run() {
try {
synchronized (b) {
b.start();
b.join();
for (int i = 0; i < Integer.MAX_VALUE; i++) {
Math.random();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
b run begin timer=1525599034475
bService timer=1525599035477
b run end timer=1525599039485

  6.方法join()后面的代码提前运行:出现意外

  示例:程序运行后,有可能会出现两种不同的结果。

package extthread;

public class ThreadA extends Thread {
private ThreadB b; public ThreadA(ThreadB b) {
super();
this.b = b;
} @Override
public void run() {
try {
synchronized (b) {
System.out.println("begin A ThreadName="
+ Thread.currentThread().getName() + " "
+ System.currentTimeMillis());
Thread.sleep(5000);
System.out.println(" end A ThreadName="
+ Thread.currentThread().getName() + " "
+ System.currentTimeMillis());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package extthread;

public class ThreadB extends Thread {
@Override
synchronized public void run() {
try {
System.out.println("begin B ThreadName="
+ Thread.currentThread().getName() + " "
+ System.currentTimeMillis());
Thread.sleep(5000);
System.out.println(" end B ThreadName="
+ Thread.currentThread().getName() + " "
+ System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package test.run;

import extthread.ThreadA;
import extthread.ThreadB; public class Run1 {
public static void main(String[] args) {
try {
ThreadB b = new ThreadB();
ThreadA a = new ThreadA(b);
a.start();
b.start();
b.join(2000);
System.out.println(" main end "+ System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}

  结果1:

  ①b.join(2000);方法先抢到B锁,然后将B锁进行释放。

  ②线程A抢到锁,打印线程A begin,并且sleep(5000);

  ③线程A打印end,并且释放锁。

  ④这时join(2000)和线程B争抢锁,而join(2000)再次抢到锁,发现时间已过,释放锁后打印main end。

  ⑤线程B抢到锁打印begin。

  ⑥线程B在5秒之后再打印end。

begin A ThreadName=Thread-1  1525599339904
end A ThreadName=Thread-1 1525599344908
main end 1525599344908
begin B ThreadName=Thread-0 1525599344909
end B ThreadName=Thread-0 1525599349916

  结果2:

  ①b.join(2000);方法先抢到B锁,然后将B锁进行释放。

  ②线程A抢到锁,打印线程A begin,并且sleep(5000);

  ③线程A打印end,并且释放锁。

  ④这时join(2000)和线程B争抢锁,线程B抢到锁后执行sleep(5000)后释放锁后打印end。

  ⑤main end在最后输出。

begin A ThreadName=Thread-0  1525599613121
end A ThreadName=Thread-0 1525599618124
begin B ThreadName=Thread-1 1525599618124
end B ThreadName=Thread-1 1525599623124
main end 1525599623124

  结果3:

  ①b.join(2000);方法先抢到B锁,然后将B锁进行释放。

  ②线程A抢到锁,打印线程A begin,并且sleep(5000);

  ③线程A打印end,并且释放锁。

  ④这时join(2000)和线程B争抢锁,而join(2000)再次抢到锁,发现时间已过,释放锁后打印main end。

  ⑤线程B抢到锁打印begin。

  ⑥这时main end也异步输出。

  ⑦线程B打印end。

begin A ThreadName=Thread-0  1525599613121
end A ThreadName=Thread-0 1525599618124
begin B ThreadName=Thread-1 1525599618124
main end 1525599618124
end B ThreadName=Thread-1 1525599623124

  7.方法join()后面的代码提前运行:解释意外

  示例:为了解释原因,用RunFirst.java进行测试,RunFirst.java类的代码中仅仅少了join(2000);这行代码。从输出结果对比可以发现,main end往往都是第一个打印的。所以可以确定的是,方法join(2000)大部分是先运行的,也就是先抢到线程B的锁,然后快速进行释放。

package test.run;

import extthread.ThreadA;
import extthread.ThreadB; public class RunFirst { public static void main(String[] args) {
ThreadB b = new ThreadB();
ThreadA a = new ThreadA(b);
a.start();
b.start();
System.out.println(" main end=" + System.currentTimeMillis());
} }
   main end=1525599679501
begin A ThreadName=Thread-0 1525599679501
end A ThreadName=Thread-0 1525599684510
begin B ThreadName=Thread-1 1525599684511
end B ThreadName=Thread-1 1525599689515

  三、类ThreadLocal的使用

  变量值的共享可以使用public static变量的形式,所有的线程都使用同一个public static变量。如果想实现每一个线程都有自己的共享变量,就需要使用JDK中提供的ThreadLocal类。

  ThreadLocal类主要解决的就是每个线程绑定自己的值,可以将ThreadLocal类类比喻成全局存放数据的盒子,盒子中可以存储每个线程的私有数据。

  1.方法get()与null

  示例:从运行结果可以看出,第一次调用tl对象的get()方法时返回的值是null,通过调用set()方法赋值后顺利取出值并打印出来。ThreadLocal解决的是变量在不同线程间的隔离性,也就是不同线程拥有自己的值,不同线程的值是可以放入ThreadLocal类中进行保存的。

package test;

public class Run {
public static ThreadLocal<String> tl = new ThreadLocal<String>(); public static void main(String[] args) {
if (tl.get() == null) {
System.out.println("get为null时候的打印");
tl.set("给定的值!");
}
System.out.println(tl.get());
System.out.println(tl.get());
} }
get为null时候的打印
给定的值!
给定的值!

  2.验证线程变量的隔离性

  示例1:从输出结果可以看出,虽然3个线程都向tl对象中set()数据值,但是每个线程还是能取出自己的数据,说明了数据的隔离性。

package tools;

public class Tools {

    public static ThreadLocal<String> tl = new ThreadLocal<String>();

}
package extthread;

import tools.Tools;

public class ThreadA extends Thread {

    @Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
if (Tools.tl.get() == null) {
Tools.tl.set("ThreadA" + (i + 1));
} else {
System.out.println("ThreadA get Value=" + Tools.tl.get());
}
Thread.sleep(200);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
package extthread;

import tools.Tools;

public class ThreadB extends Thread {

    @Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
if (Tools.tl.get() == null) {
Tools.tl.set("ThreadB" + (i + 1));
} else {
System.out.println("ThreadB get Value=" + Tools.tl.get());
}
Thread.sleep(200);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
ThreadB get Value=Main1
ThreadA get Value=Main1
Main get Value=Main1
Main get Value=Main2
ThreadB get Value=Main2
ThreadA get Value=Main2
Main get Value=Main3
ThreadA get Value=Main3
ThreadB get Value=Main3
ThreadA get Value=Main4
Main get Value=Main4
ThreadB get Value=Main4
ThreadB get Value=Main5
ThreadA get Value=Main5
Main get Value=Main5
Main get Value=Main6
ThreadA get Value=Main6
ThreadB get Value=Main6
...

  示例2:线程B在线程A启动1000毫秒之后才启动,从输出结果也可以看出,线程A输出的时间不影响线程B输出的时间。

package tools;

import java.util.Date;

public class Tools {

    public static ThreadLocal<Date> tl = new ThreadLocal<Date>();

}
package extthread;

import java.util.Date;
import tools.Tools; public class ThreadA extends Thread { @Override
public void run() {
try {
for (int i = 0; i < 20; i++) {
if (Tools.tl.get() == null) {
Tools.tl.set(new Date());
}
System.out.println("A " + Tools.tl.get().getTime());
Thread.sleep(100);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
package extthread;

import java.util.Date;

import tools.Tools;

public class ThreadB extends Thread {

    @Override
public void run() {
try {
for (int i = 0; i < 20; i++) {
if (Tools.tl.get() == null) {
Tools.tl.set(new Date());
}
System.out.println("B " + Tools.tl.get().getTime());
Thread.sleep(100);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
package test;

import extthread.ThreadA;
import extthread.ThreadB; public class Run { public static void main(String[] args) {
try {
ThreadA a = new ThreadA();
a.start(); Thread.sleep(1000); ThreadB b = new ThreadB();
b.start();
} catch (InterruptedException e) {
e.printStackTrace();
} } }
A 1525615562052
A 1525615562052
A 1525615562052
A 1525615562052
A 1525615562052
A 1525615562052
A 1525615562052
A 1525615562052
A 1525615562052
A 1525615562052
B 1525615563063
A 1525615562052
B 1525615563063
A 1525615562052
B 1525615563063
A 1525615562052
B 1525615563063
A 1525615562052
B 1525615563063
A 1525615562052
B 1525615563063
A 1525615562052
B 1525615563063
A 1525615562052
B 1525615563063
A 1525615562052
B 1525615563063
...

  3.解决get()返回null问题

  示例:通过继承ThreadLocal类并且重写initialValue方法,重新赋予返回值,这样可以使get()得到的返回值不为null,而是给定的值。

package ext;

public class ThreadLocalExt extends ThreadLocal<Object> {
@Override
protected Object initialValue() {
return "默认值但是不是null";
}
}
package test;

import ext.ThreadLocalExt;

public class Run {
public static ThreadLocalExt tl = new ThreadLocalExt(); public static void main(String[] args) {
if (tl.get() == null) {
System.out.println("为null时的输出");
tl.set("为null时给定一个值");
}
System.out.println(tl.get());
System.out.println(tl.get());
} }
默认值但是不是null
默认值但是不是null

  4.再次验证线程变量的隔离性

  示例:从输出结果可以看出,线程A在main线程执行完的1000+5000毫秒之后才开始打印,打印的数据具有隔离性,不受main线程的影响。

package ext;

import java.util.Date;

public class ThreadLocalExt extends ThreadLocal<Object> {
@Override
protected Object initialValue() {
return new Date().getTime();
}
}
package tools;

import ext.ThreadLocalExt;

public class Tools {
public static ThreadLocalExt tl = new ThreadLocalExt();
}
package extthread;

import tools.Tools;

public class ThreadA extends Thread {

    @Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
System.out.println("在线程A中取值=" + Tools.tl.get());
Thread.sleep(100);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
package test;

import tools.Tools;
import extthread.ThreadA; public class Run { public static void main(String[] args) {
try {
for (int i = 0; i < 10; i++) {
System.out.println("在main线程中取值=" + Tools.tl.get());
Thread.sleep(100);
}
Thread.sleep(5000);
ThreadA a = new ThreadA();
a.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
在main线程中取值=1525616073293
在main线程中取值=1525616073293
在main线程中取值=1525616073293
在main线程中取值=1525616073293
在main线程中取值=1525616073293
在main线程中取值=1525616073293
在main线程中取值=1525616073293
在main线程中取值=1525616073293
在main线程中取值=1525616073293
在main线程中取值=1525616073293
在线程A中取值=1525616079362
在线程A中取值=1525616079362
在线程A中取值=1525616079362
在线程A中取值=1525616079362
在线程A中取值=1525616079362
在线程A中取值=1525616079362
在线程A中取值=1525616079362
在线程A中取值=1525616079362
在线程A中取值=1525616079362
在线程A中取值=1525616079362

  四、类InheritableThreadLocal的使用

  使用InheritableThreadLocal可以在子线程中取得父线程继承下来的值。

  1.值继承

  示例:从输出结果可以看出,通过使用InheritableThreadLocalExt类,线程A可以继承main主线程的值,即使main线程执行完之后5秒线程A才开始执行。

package ext;

import java.util.Date;

public class InheritableThreadLocalExt extends InheritableThreadLocal<Object> {
@Override
protected Object initialValue() {
return new Date().getTime();
}
}
package tools;

import ext.InheritableThreadLocalExt;

public class Tools {
public static InheritableThreadLocalExt tl = new InheritableThreadLocalExt();
}
package extthread;

import tools.Tools;

public class ThreadA extends Thread {

    @Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
System.out.println("在线程A中取值=" + Tools.tl.get());
Thread.sleep(100);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
package test;

import tools.Tools;
import extthread.ThreadA; public class Run { public static void main(String[] args) {
try {
for (int i = 0; i < 10; i++) {
System.out.println("在main方法中取值=" + Tools.tl.get());
Thread.sleep(100);
}
Thread.sleep(5000);
ThreadA a = new ThreadA();
a.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
在main方法中取值=1525616443288
在main方法中取值=1525616443288
在main方法中取值=1525616443288
在main方法中取值=1525616443288
在main方法中取值=1525616443288
在main方法中取值=1525616443288
在main方法中取值=1525616443288
在main方法中取值=1525616443288
在main方法中取值=1525616443288
在main方法中取值=1525616443288
在线程A中取值=1525616443288
在线程A中取值=1525616443288
在线程A中取值=1525616443288
在线程A中取值=1525616443288
在线程A中取值=1525616443288
在线程A中取值=1525616443288
在线程A中取值=1525616443288
在线程A中取值=1525616443288
在线程A中取值=1525616443288
在线程A中取值=1525616443288

  2.值继承再修改

  示例:修改InheritableThreadLocalExt类,添加childValue方法,从输出结果可以看出,线程A从main主线程取得值后还对取到的值进行了添加值的操作。需要注意的是如果子线程在取得值的同时,主线程将InheritableThreadLocal中的值进行更改,那么子线程取到的值还是旧值。

package ext;

import java.util.Date;

public class InheritableThreadLocalExt extends InheritableThreadLocal<Object> {
@Override
protected Object initialValue() {
return new Date().getTime();
} @Override
protected Object childValue(Object parentValue) {
return parentValue + ",childValue方法的返回值!";
}
}
在main方法中取值=1525616738721
在main方法中取值=1525616738721
在main方法中取值=1525616738721
在main方法中取值=1525616738721
在main方法中取值=1525616738721
在main方法中取值=1525616738721
在main方法中取值=1525616738721
在main方法中取值=1525616738721
在main方法中取值=1525616738721
在main方法中取值=1525616738721
在线程A中取值=1525616738721,childValue方法的返回值!
在线程A中取值=1525616738721,childValue方法的返回值!
在线程A中取值=1525616738721,childValue方法的返回值!
在线程A中取值=1525616738721,childValue方法的返回值!
在线程A中取值=1525616738721,childValue方法的返回值!
在线程A中取值=1525616738721,childValue方法的返回值!
在线程A中取值=1525616738721,childValue方法的返回值!
在线程A中取值=1525616738721,childValue方法的返回值!
在线程A中取值=1525616738721,childValue方法的返回值!
在线程A中取值=1525616738721,childValue方法的返回值!

Java多线程编程(三)线程间通信的更多相关文章

  1. Java多线程编程&lpar;6&rpar;--线程间通信&lpar;下&rpar;

      因为本文的内容大部分是以生产者/消费者模式来进行讲解和举例的,所以在开始学习本文介绍的几种线程间的通信方式之前,我们先来熟悉一下生产者/消费者模式.   在实际的软件开发过程中,经常会碰到如下场景 ...

  2. Java多线程编程核心技术---线程间通信(二)

    通过管道进行线程间通信:字节流 Java提供了各种各样的输入/输出流Stream可以很方便地对数据进行操作,其中管道流(pipeStream)是一种特殊的流,用于在不同线程间直接传送数据,一个线程发送 ...

  3. Java多线程编程核心技术---线程间通信(一)

    线程是操作系统中独立的个体,但这些个体如果不经过特殊处理就不能成为一个整体.线程间的通信就是成为整体的必用方案之一.线程间通信可以使系统之间的交互性更强大,在大大提高CPU利用率的同时还会使程序员对各 ...

  4. Java多线程编程&lpar;5&rpar;--线程间通信

    一.等待与通知   某些情况下,程序要执行的操作需要满足一定的条件(下文统一将其称之为保护条件)才能执行.在单线程编程中,我们可以使用轮询的方式来实现,即频繁地判断是否满足保护条件,若不满足则继续判断 ...

  5. java多线程同步以及线程间通信详解&amp&semi;消费者生产者模式&amp&semi;死锁&amp&semi;Thread&period;join&lpar;&rpar;(多线程编程之二)

    本篇我们将讨论以下知识点: 1.线程同步问题的产生 什么是线程同步问题,我们先来看一段卖票系统的代码,然后再分析这个问题: package com.zejian.test; /** * @author ...

  6. Java并发编程:线程间协作的两种方式:wait、notify、notifyAll和Condition

    Java并发编程:线程间协作的两种方式:wait.notify.notifyAll和Condition 在前面我们将了很多关于同步的问题,然而在现实中,需要线程之间的协作.比如说最经典的生产者-消费者 ...

  7. 19、Java并发编程:线程间协作的两种方式:wait、notify、notifyAll和Condition

    Java并发编程:线程间协作的两种方式:wait.notify.notifyAll和Condition 在前面我们将了很多关于同步的问题,然而在现实中,需要线程之间的协作.比如说最经典的生产者-消费者 ...

  8. Java 并发编程:线程间的协作&lpar;wait&sol;notify&sol;sleep&sol;yield&sol;join&rpar;

    Java并发编程系列: Java 并发编程:核心理论 Java并发编程:Synchronized及其实现原理 Java并发编程:Synchronized底层优化(轻量级锁.偏向锁) Java 并发编程 ...

  9. java多线程5:线程间的通信

    在多线程系统中,彼此之间的通信协作非常重要,下面来聊聊线程间通信的几种方式. wait/notify 想像一个场景,A.B两个线程操作一个共享List对象,A对List进行add操作,B线程等待Lis ...

  10. iOS多线程编程之线程间的通信&lpar;转载&rpar;

    一.简单说明 线程间通信:在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信 线程间通信的体现 1个线程传递数据给另1个线程 在1个线程中执行完特定任务后,转到另1个线程继续执行任务 ...

随机推荐

  1. wait&lpar;&rpar; notify&lpar;&rpar;搭配synchronize的使用

    一直以为自己动多线程,使用过好像就懂了原理一样,其实是按部就班的写自己不知道原理的代码而已. 一些概念: 监视器:将监视器比作一个建筑,建筑里面有个特别的房间,房间中有一些数据,这些数据在同一个时间只 ...

  2. 清理300多台MySQL数据库的过期binlog日志

    早晨睡梦中,被 on-call了,说磁盘报警,赶紧起来打开email,收到上百封email报警,数据库磁盘不够了,查询了原因 [xxx@xxxx cacti]$ ssh xxxx "df - ...

  3. Asp &period;Net MVC4笔记之目录结构

    认识MVC从目录结构开始,从基本创建开始. App_Data 文件夹:App_Data 文件夹用于存储应用程序数据. App_Start:启动文件的配置信息,包括很重要的RouteConfig路由注册 ...

  4. Pi Hybrids问题

    Pi Hybrids问题 清华大学肖秀波梁湧老师翻译的Rardin教授的<运筹学>[1]已于今年年中出版,感谢机械工业出版社张有利老师的推荐和赠书,让我能看到如此完美的千页级宏篇译著.该书 ...

  5. 8个使用JavaScript展示图片解决方案

    1. JonDesign’s SmoothGallery 2.0 SmoothGallery demo 2. (E)2 Photo Gallery (E)2 Photo Gallery demo 3. ...

  6. 怎么用ChemDraw加反应条件

    众所周知大部分化学反应都需要在一定的条件下才会发生,比较常见的条件有压力.通电.温度.光照等等.这些特定条件在化学上就叫反应条件.我们在使用ChemDraw这款化学绘图软件的时候,往往需要给我们的化学 ...

  7. Linux 入门记录:十四、网络基础

    一.IP地址 IP 地址是因特网上的每个网络节点在全球范围内的唯一标识符,一个 IP 地址唯一标识一个主机(严格来说是标识一个网卡接口 network interface card). 现在应用最为广 ...

  8. Java中几种常见的NPE问题

    1.Map下的NPE 直接上代码: Map类集合K/V能不能存储null值的情况,如下表格: 2.foreach遍历集合删除元素 在遍历集合时对元素进行add/remove操作要使用Iterator, ...

  9. 吐槽下linq to sql的分页功能

    在调试程序的时候发现一个非常奇怪的问题: 用使用linq分页,分页到第二页的时候,第二页里面有第一页里出现的数据,开始还以为是. linq语句写的有问题,调试半天,无解.后来发现是因为没有排序的缘故. ...

  10. jvm与tomcat启动优化配置

    JVM 优化 Java 的内存模型分为: Young,年轻代(易被 GC).Young 区被划分为三部分,Eden 区和两个大小严格相同的 Survivor 区,其中 Survivor 区间中,某一时 ...