Q
为什么要学习多线程通信?
A
每个线程的内部有自己的私有的线程上线文,线程之间互不干扰。为了更好的利用服务器资源,我们通常需要多个线程之间进行协作。
业务目标,A、B两个线程依次输出
package co.dianjiu.thread;
public class MyThreadNoLock {
static class MyThreadA implements Runnable{
@Override
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println("MyThreadA===>" + i);
}
}
}
static class MyThreadB implements Runnable{
@Override
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println("MyThreadB===>" + i);
}
}
}
public static void main(String[] args) {
new Thread(new MyThreadA()).start();
new Thread(new MyThreadB()).start();
}
}
执行结果
A和B两个线程执行顺序无法控制
....
MyThreadB===>48
MyThreadA===>41
MyThreadB===>49
MyThreadA===>42
MyThreadA===>43
MyThreadA===>44
MyThreadA===>45
MyThreadA===>46
MyThreadA===>47
MyThreadA===>48
MyThreadA===>49
一、使用锁进行线程通信
根据线程和锁的关系,同一时间只有一个线程持有锁。
package co.dianjiu.thread;
public class MyThreadNoLock {
private static Object lock = new Object();
static class MyThreadA implements Runnable{
@Override
public void run() {
//对象锁,同步代码块
synchronized (lock){
for (int i = 0; i < 50; i++) {
System.out.println("MyThreadA===>" + i);
}
}
}
}
static class MyThreadB implements Runnable{
@Override
public void run() {
//对象锁,同步代码块
synchronized (lock){
for (int i = 0; i < 50; i++) {
System.out.println("MyThreadB===>" + i);
}
}
}
}
public static void main(String[] args) {
new Thread(new MyThreadA()).start();
new Thread(new MyThreadB()).start();
}
}
执行结果
可以控制A先执行、然后B在执行,距离目标更近了一些
....
MyThreadA===>47
MyThreadA===>48
MyThreadA===>49
MyThreadB===>0
MyThreadB===>1
MyThreadB===>2
MyThreadB===>3....
二、使用等待通知进行通信
等待通知机制建立的基础是两个线程使用了同一个对象锁,A、B两个线程先打印自己的输出后,唤醒另一个等待的线程,然后自己进入等待状态,同时释放锁。
package co.dianjiu.thread;
public class MyThreadNoLock {
private static Object lock = new Object();
static class MyThreadA implements Runnable{
@Override
public void run() {
synchronized (lock){
for (int i = 0; i < 50; i++) {
try {
System.out.println("MyThreadA===>" + i);
lock.notify();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify();
}
}
}
static class MyThreadB implements Runnable{
@Override
public void run() {
synchronized (lock){
for (int i = 0; i < 50; i++) {
try {
System.out.println("MyThreadB===>" + i);
lock.notify();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify();
}
}
}
public static void main(String[] args) {
new Thread(new MyThreadA()).start();
new Thread(new MyThreadB()).start();
}
}
执行结果
此时我们完成了业务目标。
....
MyThreadA===>45
MyThreadB===>45
MyThreadA===>46
MyThreadB===>46
MyThreadA===>47
MyThreadB===>47
MyThreadA===>48
MyThreadB===>48
MyThreadA===>49
MyThreadB===>49
三、使用信号量进行通信
JDK提供了一个类似于“信号量”功能的类Semaphore
,我们基于volatile
关键字的自己实现的信号量通信。
package co.dianjiu.thread;
public class MyThreadVolatile {
private static volatile int signal = 0;
static class MyThreadVolatileA implements Runnable {
@Override
public void run() {
while (signal < 50) {
if(signal % 2 ==1) {
System.out.println("MyThreadA===>" + signal);
synchronized (this) {
signal=signal+1;
}
}
}
}
}
static class MyThreadVolatileB implements Runnable {
@Override
public void run() {
while (signal < 50) {
if(signal % 2 ==0) {
System.out.println("MyThreadB===>" + signal);
synchronized (this) {
signal++;
}
}
}
}
}
public static void main(String[] args) {
new Thread(new MyThreadVolatileA()).start();
new Thread(new MyThreadVolatileB()).start();
}
}
执行结果
我们可以通过自定义简单的信号量实现单双号线程的打印。
....
MyThreadA===>43
MyThreadB===>44
MyThreadA===>45
MyThreadB===>46
MyThreadA===>47
MyThreadB===>48
MyThreadA===>49
MyThreadB===>50
四、使用管道流进行通信
一般使用管道流进行多线程IO流操作。
字符流 PipedWriter
、 PipedReader
字节流 PipedOutputStream
、 PipedInputStream
package co.dianjiu.thread;
import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
public class MyThreadPipe {
static class MyReaderThread implements Runnable{
private PipedReader reader;
public MyReaderThread(PipedReader reader) {
this.reader = reader;
}
@Override
public void run() {
System.out.println("MyReaderThread");
int receive = 0;
try {
while ((receive = reader.read()) != -1) {
System.out.print((char)receive);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
static class MyWriterThread implements Runnable {
private PipedWriter writer;
public MyWriterThread(PipedWriter writer) {
this.writer = writer;
}
@Override
public void run() {
System.out.println("MyWriterThread");
int receive = 0;
try {
writer.write("https://dianjiu.co");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws IOException, InterruptedException {
PipedReader reader = new PipedReader();
PipedWriter writer = new PipedWriter();
//建立链接,进行通讯
writer.connect(reader);
new Thread(new MyReaderThread(reader)).start();
new Thread(new MyWriterThread(writer)).start();
}
}
执行结果
MyReaderThread
MyWriterThread
https://dianjiu.co
五、Join方法的深入理解
join()方法的源码
public final void join() throws InterruptedException {
//相当于等待了0毫秒,进入永远等待状态
join(0);
}
join(long)方法源码
参数1 为等待毫秒数
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
//毫秒数参数为大于0的数值
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
//等待毫秒数为0
if (millis == 0) {
//使用以this.isAlive为条件的this.wait调用循环;当线程终止时,将调用this.notifyAll方法。
while (isAlive()) {
//join()最终调用了wait(0)方法
wait(0);
}
} else {
//使用以this.isAlive为条件的this.wait调用循环;;当线程终止时,将调用this.notifyAll方法。
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
join(long, int)方法源码
参数1 等待时间毫秒数
参数2 等待时间纳秒数
public final synchronized void join(long millis, int nanos)
throws InterruptedException {
//毫秒数参数为大于0的数值
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
//纳秒数的取值范围为0-999999
if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
}
//如果纳秒数小于500000,且毫秒数为0 则等待时间为1毫秒
//如果纳秒数大于等于500000,且毫秒数为0 则等待时间为1毫秒
//如果纳秒数大于等于500000,且毫秒数不为0 则等待时间为毫秒数+1
if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
millis++;
}
//如果纳秒数和毫秒数都为0,则等待毫秒数为0,进入永远等待状态相当于join()
join(millis);
}
回顾下使用方式
package co.dianjiu.thread;public class MyThreadJoin extends Thread{ @Override public void run(){ try { System.out.println("子线程先睡一秒"); Thread.sleep(1000); System.out.println("子线程睡完一秒"); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) throws InterruptedException { MyThreadJoin a = new MyThreadJoin(); a.setName("a"); a.start(); System.out.println(a.getName() + "===>" + a.getState()); System.out.println(Thread.currentThread().getName() + "===>" + Thread.currentThread().getState()); System.out.println("主线程,没有join方法会先执行完成"); }}
子线程先睡一秒
a===>RUNNABLE
main===>RUNNABLE
主线程,没有join方法会先执行完成
子线程睡完一秒
加了join方法后
package co.dianjiu.thread;public class MyThreadJoin extends Thread{ @Override public void run(){ try { System.out.println("子线程先睡一秒"); Thread.sleep(1000); System.out.println("子线程睡完一秒"); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) throws InterruptedException { MyThreadJoin a = new MyThreadJoin(); a.setName("a"); a.start(); a.join(); System.out.println(a.getName() + "===>" + a.getState()); System.out.println(Thread.currentThread().getName() + "===>" + Thread.currentThread().getState()); System.out.println("主线程,加上join方法后会等待子线程先执行完,主线程再执行"); }}
子线程先睡一秒
子线程睡完一秒
a===>TERMINATED
main===>RUNNABLE
主线程,加上join方法后会等待子线程先执行完,主线程再执行
总结下join()方法的作用,调用了Thread的join方法,会使得当前线程进入等待状态,等待join线程执行完成后再执行当前线程。
六、Sleep方法的深入理解
sleep(long)方法源码
参数1 毫秒数
//调用的是native方法public static native void sleep(long millis) throws InterruptedException;
sleep(long, int)方法源码
参数1 毫秒数
参数2 纳秒数
public static void sleep(long millis, int nanos) throws InterruptedException { //毫秒数参数为大于0的数值 if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } //纳秒数的取值范围为0-999999 if (nanos < 0 || nanos > 999999) { throw new IllegalArgumentException( "nanosecond timeout value out of range"); } //如果纳秒数小于500000,且毫秒数为0 则睡眠时间为1毫秒 //如果纳秒数大于等于500000,且毫秒数为0 则睡眠时间为1毫秒 //如果纳秒数大于等于500000,且毫秒数不为0 则睡眠时间为毫秒数+1 if (nanos >= 500000 || (nanos != 0 && millis == 0)) { millis++; } //如果纳秒数和毫秒数都为0,则等待毫秒数为0,进入永远等待状态相当于sleep(0) sleep(millis); }
Q
sleep、join、yield、wait区别?(阿里面试题)
A
sleep(long) 、yield()都是Thread类的静态方法,都不会释放锁,但会释放CPU,两者不同的是sleep方法会进入阻塞状态,而yield会重新进入就绪状态;wait()和notify()、notifyAll() 这三个方法都是java.lang.Object的方法,会释放对象锁同时释放CPU资源,wait后进入线程等待池中等待被再次唤醒(notify随机唤醒,notifyAll全部唤醒,线程结束自动唤醒)即放入锁池中竞争同步锁;join()底层调用了wait()方法,也会释放锁,但不会释放CPU,当前运行线程调用另一个线程的join方法,当前线程进入等待池并等待另一个join线程执行完毕后才会被唤醒。
七、ThreadLocal类的深入理解
ThreadLocal为线程本地变量或线程本地存储。严格来说,ThreadLocal类并不属于多线程间的通信,而是让每个线程有自己”独立“的变量,线程之间互不影响。
八、InheritableThreadLocal类
InheritableThreadLocal类与ThreadLocal类稍有不同,Inheritable是继承的意思。它不仅仅是当前线程可以存取副本值,而且它的子线程也可以存取这个副本值。