《Java并发编程的艺术》笔记五——Java线程基础.md

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014453515/article/details/77820121

0.线程的状态

名称 说明
New 即线程刚刚创建,而并未执行
Runnable 运行状态,Java线程将操作系统中的就绪和运行两种状态笼统的称作“运行中”
Blocked 阻塞状态,表示线程阻塞于锁
Waiting 等待状态,表示线程进入等待状态,需要等待其他线程做出一些动作(通知或中断)
TimeWaiting 超时等待状态,在指定时间内自行返回
Termicaled 终止状态,表示当前线程已经执行完毕

1.启动和终止线程

1.1构造线程
线程对象在构造的时候,需要提供喜爱能撑所需要的属性,例如线程所属的线程组,线程的优先级,是否是Daemon(守护)线程等。
我们截取Thread类中对线程的初始化部分:

private void init(ThreadGroup g, Runnable target, String name,
                  long stackSize, AccessControlContext acc) {
    if (name == null) {
        throw new NullPointerException("name cannot be null");
    }
    this.name = name;
    Thread parent = currentThread();//当前线程就是该线程的父线程
    this.group = g;
    this.daemon = parent.isDaemon();
    this.priority = parent.getPriority();
    this.target = target;
    setPriority(priority);
//将父线程的InheritableThreadLocal复制过来
    if (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();
}

一个新构造的线程对象,是由其parent线程来进行空间分配的,而child线程继承了parent是否为Daemon,优先级和加载资源的contextClassLoader以及可继承的ThreadLocal,同时还会分配一个唯一的ID来标示这个child线程。初始化好之后,在堆内存中等待着运行。

1.2 启动线程

调用start方法就可以启动线程。若无其他设置,调用start方法后,线程进入到就绪状态,CPU有资源时即执行线程的run方法。

1.3 线程中断

中断表示一个运行中的线程是否被其他线程进行了中断操作。中断好比其他线程对该线程打了个招呼,其他线程通过调用该线程的interrupt()函数对其进行中断操作。

线程通过检查自身是否中断进行响应,线程通过方法isInterrupted()来判断是否被中断,也可以调用静态方法Thread.interruted()对当前线程的中断标示位进行复位。
如果该线程已处于终结状态,即使该线程被中断过,则isInterrupted()也会返回false;

1.4 安全的终止线程

中断状态是线程的一个标示位,最适合用来取消或停止任务。除了中断以外,还可以用一个boolean变量来控制是否需要终止任务并终止线程。

以下是一个例子:


public class Shutdown {
    public static void main(String[] args) {
        Runner one = new Runner();
        Thread count = new Thread(one,"CounttThread");
        count.start();
        SleepUtils.second(1);
        count.interrupt();
        Runner two = new Runner();
        count = new Thread(two,"CountThread2");
        count.start();
        SleepUtils.second(1);
        two.cancel();
    }

    static class Runner implements Runnable {
        private volatile boolean on = true;
        private long count;

        @Override
        public void run() {
            while (on && !Thread.currentThread().isInterrupted()) {
                count++;
            }
            System.out.println("count=" + count);
        }

        public void cancel() {
            on = false;
        }
    }

}

猜你喜欢

转载自blog.csdn.net/u014453515/article/details/77820121