了解Java中的线程

了解Java中的线程


        在Java中,提供了对线程的支持。用户可以定义自己的线程,并且启动执行它们。当使用到线程的时候,最好对自己的线程有所了解,什么时候启动,什么时候结束,发生异常会怎么样,是否会发生阻塞,是否可以中止,等等。只有了解了这些,线程才能真正的为我所用。

 一,线程的创建

     Java中的线程由Thread类表示,有两种方式可以创建线程,一个是实现Runnable接口,一个是继承Thread类。当用Runnable构造Thread的时候,这个Runnable对象会保存在Thread的target成员中。不管怎样,线程真正执行的内容就是Thread类的run方法,其实这个run方法也是实现的Runnable接口的run方法:

    public void run() {
        if (target != null) {
            target.run();
        }
    }

      可以想象,如果继承了Thread类却没有重写run方法,也没有设置target(即Runnable实例),那么这个线程其实什么也不会做。

      Thread的构造方法有好多个,但是他们最终都会利用一个init方法实现实例的初始化:

    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.toCharArray();

        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 (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();
    }

     创建一个子线程时,会从父线程继承一系列的配置、变量,如是否为守护线程、优先级,Classloader,ThreadLocal变量。同时也会为线程设置一个ThreadGroup线程组,一会儿再细说。

二,线程的状态

    线程有NEW、RUNNABLE、BLOCKED、WAITING、TIMED_WAITING、TERMINATED几种状态,它们被封装在了内部的State枚举中。

1. 根据JDK源码中的注释描述,新创建了一个线程对象还没有执行start()启动之前,它的状态就是NEW。

2. RUNNABLE状态说明该线程已经开始接受调度,一旦获得CPU的使用权将开始执行。在这个状态线程有可能正在执行,也可能在等待执行。

3. 表示线程阻塞的状态有三种,阻塞状态是指线程因为某种原因放弃了cpu 使用权,暂时停止运行。 

(一).  BLOCKED状态表示线程正在等待进入某个同步块或者执行同步方法,由于其他线程暂时占用同步锁,则当前线程必须阻塞等待。

(二). 进入WAITING状态的原因可能是,线程执行了Object的wait()方法、Thread的jion()方法或者LockSupport的park()方法。WAITING说明线程在等待其它线程做出某个动作,比如一个线程执行了Object的wait()方法后,它将等待另一个线程执行这个Object的notify()或者notifyAll()方法,这个线程才能再次进入RUNNABLE状态。

(). 限时等待TIMED_WAITING。有五种情况发生后可进入这个状态,Thread.sleep、Object的wait(long)、Thread的join(long)、LockSupport.parkNanos以及LockSupport.parkUntil。

4. 线程结束生命周期,则进入了TERMINATED状态。死亡的线程不可再次复生。

三,线程组ThreadGroup

     线程组ThreadGroup是为了方便线程的管理,每一个ThreadGroup都可以包含一组的子线程和一组子线程组,类似于文件系统,以树形的方式存在,通常情况下根线程组是system线程组,system线程组下是main线程组。如下可以打印出系统默认的线程组:
    public static void main(String[] s){
        Thread current = Thread.currentThread();

        System.out.println(current.getThreadGroup().getName());
        System.out.println(current.getThreadGroup().getParent().getName());
        System.out.println(current.getThreadGroup().getParent().getParent());
    }
main
system
null

    线程组可以统计组内的线程组数、线程数,统一的设置组内线程的uncaughtException()方法,统一的中断组内线程等等。但是在限时开发中,很少用到它的特性,多数开发者也不了解,好多人也不提倡甚至认为ThreadGroup就是Java中一个比较失败的设计。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值