1、 使用unsafe实现线程挂起
package com.download;
import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class UserController {
public static void main(String[] args) throws Exception {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
Unsafe unsafe = (Unsafe) field.get(null);
TestThread thread = new TestThread(unsafe);
thread.start();
thread.sleep(2000);
thread.setFlag(true);
System.out.println("2222");
}
}
class TestThread extends Thread {
boolean flag;
private Unsafe unsafe;
public TestThread(Unsafe unsafe) {
this.unsafe = unsafe;
this.setName("Fuck");
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
for (int i =0; i < 10; i++) {
if (flag)
lock();
System.out.println(this.getName() + ":" + i);
try {
this.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void lock() {
try {
// 使用park挂起线程,使用unpark可以使线程重新以运行
this.unsafe.park(false, 0L);
} catch (Exception e) {
e.printStackTrace();
}
}
}