Java多线程:线程属性

2020-06-21  本文已影响0人  垃圾简书_吃枣药丸

# 线程属性

# ID


    /* For generating thread ID */
    private static long threadSeqNumber;

    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc,
                      boolean inheritThreadLocals) {
        ...
        /* Set thread ID */
        tid = nextThreadID();
        ...
    }

    private static synchronized long nextThreadID() {
        return ++threadSeqNumber;
    }

# NAME

    private static synchronized int nextThreadNum() {
        return threadInitNumber++;
    }

# 代码演示

/**
 * @author 喜欢天文的pony站长
 * Created on 2020/6/16.
 */
public class ThreadProperties {
    private static final Logger LOGGER = LoggerFactory.getLogger(ThreadProperties.class);

    public static void main(String[] args) {
        Thread mainThread = Thread.currentThread();
        Thread childThread = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2L);
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
        });
        //必须在start()之前设置线程的优先级
        //childThread.setDaemon(true);
        childThread.start();

        LOGGER.info("main线程的id:{}", mainThread.getId());
        LOGGER.info("子线程的id:{}", childThread.getId());

        LOGGER.info("main线程的名字:{}", mainThread.getName());
        LOGGER.info("子线程的名字(修改之前):{}", childThread.getName());
        childThread.setName("childThread-1");
        LOGGER.info("子线程的名字(修改之后):{}", childThread.getName());

        LOGGER.info("main线程是否是守护线程{}", mainThread.isDaemon());
        LOGGER.info("子线程线程是否是守护线程{}", childThread.isDaemon());

        //不能在线程运行过程中设置线程的优先级
        childThread.setDaemon(true);
        LOGGER.info("子线程线程是否是守护线程{}", childThread.isDaemon());

    }
}

image.png

欢迎在评论区留下你看文章时的思考,及时说出,有助于加深记忆和理解,还能和像你一样也喜欢这个话题的读者相遇~

# 系列文章

上一篇下一篇

猜你喜欢

热点阅读