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 0000000000000000000000000000000000000000..fff6f3d00aebef13381e922e2d8631f5c40a3343 --- /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); + } +}