思路:
开三个线程A,B,C
线程A不断的调用LockSupport.park()阻塞自己,一旦发现自己被唤醒,调用Thread.interrupted()清除interrupt标记位,同时增加自增计数
线程B不断的调用线程A的interrupt()方法,将线程A从阻塞中唤醒,一旦唤醒成功,则自增计数
线程C定时输出计数
代码如下
1 import java.util.concurrent.atomic.AtomicInteger; 2 import java.util.concurrent.locks.LockSupport; 3 4 /** 5 * Created by cc on 2017/2/6. 6 */ 7 public class Test { 8 public static void main(String[] args) { 9 final AtomicInteger count = new AtomicInteger(0); 10 final Thread thread = new Thread(new Runnable() { 11 public void run() { 12 while (true) { 13 LockSupport.park(); 14 Thread.interrupted();//clear interrupt flag 15 } 16 } 17 }); 18 19 for(int i =0;i<1;i++) { 20 new Thread(new Runnable() { 21 public void run() { 22 while (true) { 23 if (!thread.isInterrupted()) { 24 thread.interrupt(); 25 count.incrementAndGet(); 26 } 27 } 28 } 29 }).start(); 30 } 31 new Thread(new Runnable() { 32 public void run() { 33 long last = 0; 34 while (true) { 35 try { 36 Thread.sleep(1000); 37 System.out.println(String.format("thread park %d times in 1s", count.get() - last)); 38 last = count.get(); 39 } catch (InterruptedException e) { 40 e.printStackTrace(); 41 } 42 } 43 } 44 }).start(); 45 46 thread.start(); 47 } 48 }