标签:03 通讯 Thread res 线程 new 多线程 public wait
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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。