JDK新特性(三) -----unsafe

引用别人的

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();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值