线程之间的通信
来源:互联网 发布:mac视频播放器下载 编辑:程序博客网 时间:2024/06/06 01:46
线程的join用法
class MyThread extends Thread{ @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("sub Thread"); }}public class Main { public static void main(String[] args) { MyThread thread=new MyThread(); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("main thread"); }}
运行结果:
sub Thread
main thread
join
thread.Join把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。
如果一个线程A执行了thread.join()语句,含义是:当前线程A等待thread线程终止之后也从thread.join()返回
thread.join还可以指定超时时间
wait notify
几个注意点:
wait 与 notify/notifyAll 方法必须在同步代码块中使用,即要先对调用对象加锁。
当线程执行wait()时,会把当前的锁释放,然后让出CPU,进入等待状态。
当执行notify/notifyAll方法时,会唤醒一个处于等待该 对象锁 的线程,然后继续往下执行,直到执行完退出对象锁锁住的区域(synchronized修饰的代码块)后再释放锁。
从这里可以看出,notify/notifyAll()执行后,并不立即释放锁,而是要等到执行完临界区中代码后,再释放。故,在实际编程中,我们应该尽量在线程调用notify/notifyAll()后,立即退出临界区。即不要在notify/notifyAll()后面再写一些耗时的代码
package cn.itcast.heima2;public class TraditionalThreadCommunication { /** * 线程之间的通信 */ public static void main(String[] args) { final Business business = new Business(); new Thread( new Runnable() { @Override public void run() { for(int i=1;i<=5;i++){ business.sub(i); } } } ).start(); for(int i=1;i<=5;i++){ business.main(i); } }} class Business { private boolean bShouldSub = true; public synchronized void sub(int i){ while(!bShouldSub){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for(int j=1;j<=5;j++){ System.out.println("sub thread sequence of " + j + ",loop of " + i); } bShouldSub = false; this.notify(); } public synchronized void main(int i){ while(bShouldSub){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for(int j=1;j<=5;j++){ System.out.println("main thread sequence of " + j + ",loop of " + i); } bShouldSub = true; this.notify(); } }
上面的代码就是
子线程先打印5下,在主线程打印5下。一个循环5次。
notify,wait,join详解
阅读全文
0 0
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- 线程之间的通信
- java线程之间的通信
- 多线程-线程之间的通信
- linux线程之间的通信
- javaBean验证框架(3)—验证消息
- 三大范式
- 【VS2012】绝对的偶遇
- java中JOptionPane类的四种对话框简单应用
- web复选框的传值问题
- 线程之间的通信
- Differential privacy
- Web static server
- 深入理解java对象序列化
- tarjan 缩点
- 为什么java程序要public static void main(String[ ] args)方法
- 逆波兰表达式递归求值
- Servlet之文件上传与下载
- 无线视频传输任务的进展与问题