|
| 1 | +public class UnsafeTest { |
| 2 | + |
| 3 | + public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException { |
| 4 | + Field f = Unsafe.class.getDeclaredField("theUnsafe"); |
| 5 | + f.setAccessible(true); |
| 6 | + Unsafe unsafe = (Unsafe) f.get(null); |
| 7 | + Thread t1 = new Thread() { |
| 8 | + @Override |
| 9 | + public void run() { |
| 10 | + Thread.currentThread().setName("t1"); |
| 11 | + System.out.println(Thread.currentThread().getName() + " before park"); |
| 12 | + //park 100 seconds |
| 13 | + unsafe.park(false, TimeUnit.NANOSECONDS.convert(100, TimeUnit.SECONDS)); |
| 14 | + System.out.println(Thread.currentThread().getName() + " after park"); |
| 15 | + } |
| 16 | + }; |
| 17 | + Thread t2 = new Thread() { |
| 18 | + @Override |
| 19 | + public void run() { |
| 20 | + try { |
| 21 | + Thread.currentThread().setName("t2"); |
| 22 | + TimeUnit.SECONDS.sleep(1); |
| 23 | + System.out.println(Thread.currentThread().getName() + " unpark t1"); |
| 24 | + unsafe.unpark(t1); |
| 25 | + } catch (InterruptedException e) { |
| 26 | + e.printStackTrace(); |
| 27 | + } |
| 28 | + |
| 29 | + } |
| 30 | + }; |
| 31 | + Thread t3 = new Thread() { |
| 32 | + @Override |
| 33 | + public void run() { |
| 34 | + Thread.currentThread().setName("t3"); |
| 35 | + System.out.println(Thread.currentThread().getName() + " park 5 seconds"); |
| 36 | + //park 5 seconds |
| 37 | + unsafe.park(true, System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5,TimeUnit.SECONDS)); |
| 38 | + System.out.println(Thread.currentThread().getName() + " after park"); |
| 39 | + } |
| 40 | + }; |
| 41 | + t1.start(); |
| 42 | + t2.start(); |
| 43 | + t3.start(); |
| 44 | + try { |
| 45 | + t1.join(); |
| 46 | + t2.join(); |
| 47 | + t3.join(); |
| 48 | + } catch (InterruptedException e) { |
| 49 | + e.printStackTrace(); |
| 50 | + } |
| 51 | + } |
| 52 | +} |
0 commit comments