From 5de4ce009914efc16cb36460bf55bf4b2e9b6545 Mon Sep 17 00:00:00 2001 From: jlhde123 ASUS <472327024@qq.com> Date: Sun, 12 Mar 2017 11:01:19 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20join,wait=20=E7=9A=84?= =?UTF-8?q?=E5=AD=A6=E4=B9=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../jlh/viewer/thread/ThreadJoinTestList.java | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 jlh/src/main/java/com/jlh/viewer/thread/ThreadJoinTestList.java diff --git a/jlh/src/main/java/com/jlh/viewer/thread/ThreadJoinTestList.java b/jlh/src/main/java/com/jlh/viewer/thread/ThreadJoinTestList.java new file mode 100644 index 0000000..fff6f3d --- /dev/null +++ b/jlh/src/main/java/com/jlh/viewer/thread/ThreadJoinTestList.java @@ -0,0 +1,65 @@ +package com.jlh.viewer.thread; + +import java.util.concurrent.TimeUnit; + +/** + * com.jlh.viewer.thread + * Created by ASUS on 2017/3/12. + * 10:13 + */ +public class ThreadJoinTestList { + public static void main(String[] args) throws InterruptedException { + // sleep 方法不释放锁,wait释放锁 + // join 方法会使调用此访问的线程等待 目标对象完成之前 陷入等待,,用于控制顺序 + // 前提是目标对象线程还活着,或者已经启动,否则是不会阻塞的 通过调用本地方法 native isalive 来判断线程是否存活 + // join的参数 long 是指 线程多久检查一次,默认是一只循环检查 加入, 一旦wait对象锁有了,就会立刻获取,而不会一定等到指定时间获取 + Thread t1=new Thread(()->{ + try { + TimeUnit.SECONDS.sleep(3); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("one start"); + }); + Thread t2=new Thread(()->{ + try { + t1.join(10*1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("two start"); + }); + t2.start(); + t1.start(); + + ThreadJoinTestList threadJoinTestList = new ThreadJoinTestList(); + new Thread(()->{ + for (int i=0;i<10;i++){ + try { + TimeUnit.MILLISECONDS.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + try { + threadJoinTestList.do2(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }).start(); + threadJoinTestList.do1(); + + + } + + public synchronized void do1() throws InterruptedException { + for (int i=0;i<10;i++){ + this.wait(3000); + System.out.println(i); + } + } + public synchronized void do2() throws InterruptedException { + this.notifyAll(); +// TimeUnit.SECONDS.sleep(10); + } +} -- Gitee