前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java并发-8.线程的构造启动,中断,完成

Java并发-8.线程的构造启动,中断,完成

作者头像
悠扬前奏
发布2019-05-28 13:19:59
4640
发布2019-05-28 13:19:59
举报

1. 构造线程

运行线程前需要构造线程对象,这一步在Thread类的初始化部分(以下为init方法的源码):

代码语言:javascript
复制
    /**
     * Initializes a Thread.
     *
     * @param g the Thread group
     * @param target the object whose run() method gets called
     * @param name the name of the new Thread
     * @param stackSize the desired stack size for the new thread, or
     *        zero to indicate that this parameter is to be ignored.
     * @param acc the AccessControlContext to inherit, or
     *            AccessController.getContext() if null
     * @param inheritThreadLocals if {@code true}, inherit initial values for
     *            inheritable thread-locals from the constructing thread
     */
    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc,
                      boolean inheritThreadLocals) {
        if (name == null) {
            throw new NullPointerException("name cannot be null");
        }

        this.name = name;

        Thread parent = currentThread();
        SecurityManager security = System.getSecurityManager();
        if (g == null) {
            /* Determine if it's an applet or not */

            /* If there is a security manager, ask the security manager
               what to do. */
            if (security != null) {
                g = security.getThreadGroup();
            }

            /* If the security doesn't have a strong opinion of the matter
               use the parent thread group. */
            if (g == null) {
                g = parent.getThreadGroup();
            }
        }

        /* checkAccess regardless of whether or not threadgroup is
           explicitly passed in. */
        g.checkAccess();

        /*
         * Do we have the required permissions?
         */
        if (security != null) {
            if (isCCLOverridden(getClass())) {
                security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
            }
        }

        g.addUnstarted();

        this.group = g;
        this.daemon = parent.isDaemon();
        this.priority = parent.getPriority();
        if (security == null || isCCLOverridden(parent.getClass()))
            this.contextClassLoader = parent.getContextClassLoader();
        else
            this.contextClassLoader = parent.contextClassLoader;
        this.inheritedAccessControlContext =
                acc != null ? acc : AccessController.getContext();
        this.target = target;
        setPriority(priority);
        if (inheritThreadLocals && parent.inheritableThreadLocals != null)
            this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
        /* Stash the specified stack size in case the VM cares */
        this.stackSize = stackSize;

        /* Set thread ID */
        tid = nextThreadID();
    }

可以看到,初始化线程的时候需要提供一些属性:所属线程组,线程优先级,是否Daemon等。且都是根据其parent线程进行空间分配的。

2. 启动线程

线程初始化之后,调用start()方法就能启动这个线程。

3. 中断

  • 中断可以视作线程的一个标识位属性,标识一个运行中的线程是否被其他线程进行了中断操作。
  • 其他线程可以通过调用该线程的interrupt()方法对其进行中断操作
  • isInterrupted()方法判断是否被中断,终结状态的线程返回false
  • 静态方法Thread.interrupted()方法对当前线程的中断位进行复位。
  • 抛出InterruptedException之前,JVM会清除线程中断位,所以此时调用isInterrupted()方法返回false

代码示例:

代码语言:javascript
复制
import java.util.concurrent.TimeUnit;

/**
 * SleepThread不停睡眠,BusyThread一直运行,分别中断,观察两者中断标识位
 *
 * @author pengjunzhe
 */
public class Interrupted {
    public static void main(String[] args) throws Exception {
        // sleepThread 不停的睡眠
        Thread sleepThread = new Thread(new SleepRunner(), "SleepThread");
        sleepThread.setDaemon(true);
        // busyThread 一直运行
        Thread busyThread = new Thread(new BusyRunner(), "BusyThread");
        busyThread.setDaemon(true);
        sleepThread.start();
        busyThread.start();

        // 休眠5秒,让sleepThread和busyThread充分运行
        TimeUnit.SECONDS.sleep(5);
        sleepThread.interrupt();
        busyThread.interrupt();
        System.out.println("SleepThread is " + sleepThread.isInterrupted());
        System.out.println("BusyThread is " + busyThread.isInterrupted());

        // 防止两者立刻退出
        SleepUtils.second(2);

    }

    static class SleepRunner implements Runnable {
        @Override
        public void run() {
            while (true) {
                SleepUtils.second(10);
            }
        }
    }

    static class BusyRunner implements Runnable {
        @Override
        public void run() {
            while (true) {
            }
        }
    }
}

代码输出:

代码语言:javascript
复制
SleepThread is false
BusyThread is true
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at java.lang.Thread.sleep(Thread.java:340)
    at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
    at com.junzerg.threads.SleepUtils.second(SleepUtils.java:11)
    at com.junzerg.threads.Interrupted$SleepRunner.run(Interrupted.java:39)
    at java.lang.Thread.run(Thread.java:748)

可以看到,抛出InterruptedException的线程SleepThread的中断位被清除了。运行中的BusyThread中断位没有被清除。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.05.07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 构造线程
  • 2. 启动线程
  • 3. 中断
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档