java线程之isAlive方法,sleep方法,和getId方法


  • isAlive方法
  • sleep方法
  • getId方法

isAlive方法

isAlive方法,即线程的活动情况,参考一下前面线程中讲到的,线程的几种状态。有一个就绪和运行状态,指的就是Alive状态。
所以活动状态其实就是线程已经启动了,并且没有停止的这个中间过程状态
源码:

/**
     * Tests if this thread is alive. A thread is alive if it has
     * been started and has not yet died.
     *
     * @return  <code>true</code> if this thread is alive;
     *          <code>false</code> otherwise.
     */
    public final native boolean isAlive();

从上面的解释其实也可以看到,线程start了,并且没有died的中间状态

在测试这个状态的时候需要注意的是,是否是你对应的当前线程的活跃度的情况,参考之前的this,和currentThread。


sleep方法

sleep方法其实很简单,如果在java中应用的话,其实没有太多弯弯绕绕的,但是如果在android中的话,就需要注意了,注意当前的运行环境是否是主线程。因为线程只有在start启动后,才算是一个异步过程,如果仅仅只是run了一下,其实还是同步过程,在主线程中,对比的话,也同样是需要参考this,和currentThread的
简单low一下源码:

/**
     * Causes the currently executing thread to sleep (temporarily cease
     * execution) for the specified number of milliseconds, subject to
     * the precision and accuracy of system timers and schedulers. The thread
     * does not lose ownership of any monitors.
     *
     * @param  millis
     *         the length of time to sleep in milliseconds
     *
     * @throws  IllegalArgumentException
     *          if the value of {@code millis} is negative
     *
     * @throws  InterruptedException
     *          if any thread has interrupted the current thread. The
     *          <i>interrupted status</i> of the current thread is
     *          cleared when this exception is thrown.
     */
    public static native void sleep(long millis) throws InterruptedException;

它的解释是,会导致当前执行代码块的线程进行一段时间的休眠。
其实在线程中的休眠有两个方法,一个方法是sleep过程,另外一个就是wait的过程。需要做个简单的区分,因为sleep是在执行过程的内部进行休眠,如果其持有锁的话,是不会去释放锁不会释放资源的,但是wait不一样,wait可以理解为等待的意思,这个时候它会把锁给释放。


getId方法

getId顾名思义,其实就是获取线程ID的意思,同时还有一个getName的方法,做个简单的区分,每个线程在生成的时候都是有唯一一个固定的ID的,但是对应的Name是通过set方法设置,或者线程按照自己的编号进行默认生成的过程,这就导致的。其实Name是可以重复的。而ID则不允许重复

源码:
获取线程ID的源码部分

/**
     * Returns the identifier of this Thread.  The thread ID is a positive
     * <tt>long</tt> number generated when this thread was created.
     * The thread ID is unique and remains unchanged during its lifetime.
     * When a thread is terminated, this thread ID may be reused.
     *
     * @return this thread's ID.
     * @since 1.5
     */
    public long getId() {
        return tid;
    }
/*
     * Thread ID
     */
    private long tid;

通过threadSeqNumber自增来进行编排的

/* Set thread ID */
 tid = nextThreadID();
private static synchronized long nextThreadID() {
        return ++threadSeqNumber;
    }

一小段测试代码:

package com.zzf.java.charpter1.part10;

import java.util.Date;

/**
 * 线程的构造函数在别的线程中被调用,这个时候当前调用的线程的ID为1
 * 注意区分的概念就是:当前线程和当前调用的线程。
 * isAlive
 * isAlive描述的是线程的活跃度。即活动状态,这种状态指的是已经start启动并且没有终止的状态
 * this.isAlive是当前进程的活跃情况,在这里当然指的就是当前对象,因为线程没有start起来,所以isAlive是false,而由于此段代码是在主线程中去调用,所以主线程的活跃状态为true
 * 
 * getId
 * Id才是线程的唯一标示,因为Name是可以重名的,但是Id是不会重名的
 * 
 * sleep方法
 * sleep一般指的是线程的休眠时间,因为已经区分过了,只有在start启动,或者run被别的线程调用的时候,这个时候才会有在子线程中睡眠这一说,如果在主线程中去调用的话,导致主线程睡眠,
 * 在子线程中调用的话,这个是不会影响主线程的
 * 
 * @author zhouzhangfei
 *
 */
public class MyThread10 extends Thread{
    public MyThread10() {
        // TODO Auto-generated constructor stub
        System.out.println("this.getName:"+this.getName()+"\t"+"currentThread.getName:"+Thread.currentThread().getName());
        System.out.println("this.getId:"+this.getId()+"\t"+"currentThread.getId:"+Thread.currentThread().getId());
        System.out.println("this.isAlive:"+this.isAlive()+"\tcurrentThread.isAlived:"+currentThread().isAlive());

        System.out.println("beforesleep:"+System.currentTimeMillis());
        try {
            //主线程中去睡眠了2000ms
            sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("aftersleep:"+System.currentTimeMillis());
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();
        System.out.println("run:\t"+"this.isAlive:"+this.isAlive()+"\tcurrentThread.isAlived:"+Thread.currentThread().isAlive()+"\tcurrentThread.getName:"+
        Thread.currentThread().getName()+"\tgetId:"+Thread.currentThread().getId());
        System.out.println("run\tbeforesleep:"+System.currentTimeMillis()+"\tcurrentThreadId:"+Thread.currentThread().getId());
        try {
            sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("run\taftersleep:"+System.currentTimeMillis()+"\tcurrentThreadId:"+Thread.currentThread().getId());
    }
}
package com.zzf.java.charpter1.part10;

public class Part10Main {
    public static void main(String[] args) {
        MyThread10 myThread10 = new MyThread10();

        Thread mtThread = new Thread(myThread10);
        mtThread.setName("ABC");
        mtThread.start();   
        myThread10.start();

        Thread mtThread2 = new Thread(myThread10);
        mtThread2.setName("ABC");
        mtThread2.start();
    }
}

输出的结果为:

this.getName:Thread-0   currentThread.getName:main
this.getId:9    currentThread.getId:1
this.isAlive:false  currentThread.isAlived:true
beforesleep:1516756915153
aftersleep:1516756917158
run:    this.isAlive:true   currentThread.isAlived:true currentThread.getName:ABC   getId:10
run:    this.isAlive:true   currentThread.isAlived:true currentThread.getName:Thread-0  getId:9
run beforesleep:1516756917159   currentThreadId:9
run beforesleep:1516756917159   currentThreadId:10
run:    this.isAlive:true   currentThread.isAlived:true currentThread.getName:ABC   getId:11
run beforesleep:1516756917159   currentThreadId:11
run aftersleep:1516756919163    currentThreadId:10
run aftersleep:1516756919163    currentThreadId:9
run aftersleep:1516756919163    currentThreadId:11

以上就是针对isAlive,sleep和getId简单的一些分析