03 - 多线程之间如何实现通讯
作者:互联网
Java 多线程之间如何实现通讯
多个线程之间通过wait,notify通讯
public class Thread007 {
class Res {
public String userName;
public char userSex;
public boolean flag;
}
class InputThread extends Thread {
private Res res;
public InputThread(Res res) {
this.res = res;
}
@Override
public void run() {
try {
int count = 0;
while (true) {
synchronized (res) {
if (this.res.flag) {
res.wait();
}
if (count == 0) {
this.res.userName = "小薇";
this.res.userSex = '女';
} else {
this.res.userName = "余胜军";
this.res.userSex = '男';
}
this.res.flag = true;
this.res.notify();
}
count = (count + 1) % 2;
}
} catch (Exception e) {
}
}
}
class OutThread extends Thread {
private Res res;
public OutThread(Res res) {
this.res = res;
}
@Override
public void run() {
while (true) {
try {
synchronized (res) {
if (!res.flag) {
res.wait();
}
System.out.println(res.userName + "," + res.userSex);
res.flag = false;
res.notify();
}
} catch (Exception e) {
}
}
}
}
public static void main(String[] args) {
new Thread007().start();
}
private void start() {
Res res = new Res();
InputThread inputThread = new InputThread(res);
OutThread outThread = new OutThread(res);
inputThread.start();
outThread.start();
}
}
Wait、Notify()用法
-
因为涉及到对象锁, wait、Notify 必须要在synchronized中使用
-
Wait会暂停当前线程,释放cpu执行资格,同时释放锁。
-
Notify 唤醒锁池正在等待的线程
wait和sleep的区别
都是可以让当前的线程变为阻塞状态。
wait可以释放锁。
为什么wait要放在object类
因为 synchronized 可以使用任意对象作为锁。
多线程 join
使用 join,报这个线程的顺序问题,比如有A和B两个线程,如果在B线程调用A.join方法,B线程会阻塞同时释放锁,则必须先让A线程执行完毕,才能执行B线程,底层通过wait和notify实现。
public class Thread009 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "," + i);
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new Thread009(), "t1");
Thread t2 = new Thread(new Thread009(), "t2");
Thread t3 = new Thread(new Thread009(), "t3");
try {
t1.start();
// 主线程调用 t1.join(),主线程变为阻塞状态,同时释放锁,必须等待t1线程执行完毕的情况下,主线程才能继续执行
t1.join();
t2.start();
t2.join();
t3.start();
t3.join();
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "," + i);
}
// 这样,最终效果跟单线程一样
} catch (Exception e) {
e.printStackTrace();
}
}
}
标签:03,通讯,Thread,res,线程,new,多线程,public,wait 来源: https://www.cnblogs.com/YeQuShangHun/p/16594737.html