JAVA多线程之(join)
2016-01-21 20:12
573 查看
java多线程中,join方法是主线程等待一个子线程结束后再继续执行主线程后续代码,wait方法会让线程进入阻塞状态,并且会释放线程占有的锁,并交出CPU执行权限,由于wait方法会让线程释放对象锁,研究java
Thread类的join方法发现,其实join方法也是调用wait方法实现,所以join方法同样会让线程释放对一个对象持有的锁。
Thread类的join方法的源代码:
输出:
i:11
线程Thread-0进入睡眠状态
线程Thread-0睡眠结束
i:12
----------主线程已经等到了子线程执行结束,继续执行主线程--------
Thread类的join方法发现,其实join方法也是调用wait方法实现,所以join方法同样会让线程释放对一个对象持有的锁。
Thread类的join方法的源代码:
/** * Waits at most <code>millis</code> milliseconds for this thread to * die. A timeout of <code>0</code> means to wait forever. * * @param millis the time to wait in milliseconds. * @exception InterruptedException if any thread has interrupted * the current thread. The <i>interrupted status</i> of the * current thread is cleared when this exception is thrown. */ 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; } } }Thread join 方法实例代码如下:
package nc.com.thread.traditional.example; /** * @ClassName: ThreadJoin * @Description: TODO(这里用一句话描述这个类的作用) * @author A18ccms a18ccms_gmail_com * @date 2015-12-19 下午06:35:15 * */ public class ThreadJoin { private Object object = new Object(); private int i = 10; public static void main(String[] args) { /** * 有join时输出: */ ThreadJoin j = new ThreadJoin(); DemoThread t1 = j.new DemoThread(); t1.start(); try { //执行join方法后,主线程进入阻塞状态,直到子线程执行结束 t1.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("----------主线程已经等到了子线程执行结束,继续执行主线程--------"); } class DemoThread extends Thread{ @Override public void run() { synchronized (object) { i++; System.out.println("i:"+i); try { System.out.println("线程"+Thread.currentThread().getName()+"进入睡眠状态"); } catch (Exception e) { // TODO: handle exception } System.out.println("线程"+Thread.currentThread().getName()+"睡眠结束"); i++; System.out.println("i:"+i); } } } }
输出:
i:11
线程Thread-0进入睡眠状态
线程Thread-0睡眠结束
i:12
----------主线程已经等到了子线程执行结束,继续执行主线程--------
相关文章推荐
- eclipse 单机版 mahout collaborative demo
- java正则表达式
- JAVA基础(一)重载和复写
- JAVA内部类使用,什么时候该使用内部类及使用内部类的好处
- hibernate Session的几个简单方法
- flask之行(Eclipse+Pydev IDE)
- java基础学习
- java中接口和类【转】
- spring IOC
- JAVA多线程之(wait notify)
- d3结合Spring和mybatis实现数据可视化中数据库内容的树型显示
- ssh(Spring struts2 hibernate)整合
- Spring structs2 hibernate 整合(ssh)
- [Java Performance] 数据库性能最佳实践 - JPA缓存
- Java问题定位
- JavaBean与内省
- 搭建Spring4.1与Spring4.2 websock+stomp+activeMQ需要注意事项:spring4不同版本websocket差异
- 百度翻译开放接口JAVA实现
- 获取Spring容器Bean
- studio--如何将Eclipse中的项目迁移到Android Studio 中