Java并发编程初级篇(二):Java线程基本信息
Java并发编程初级篇(二):Java线程基本信息
阿拉德大陆的魔法师 发表于1年前
Java并发编程初级篇(二):Java线程基本信息
  • 发表于 1年前
  • 阅读 28
  • 收藏 0
  • 点赞 0
  • 评论 0

标题:腾讯云 新注册用户域名抢购1元起>>>   

摘要: 如何获取和设置线程的基本信息?

Thread类的基本信息:

  1. ID:线程唯一标识符
  2. Name:线程名称
  3. Priority:线程对象的优先级。范围为从1到10,其中1为最低优先级,10为最高优先级。
  4. Status:线程的状态。在Java中线程有6种状态:NEW,RUNNABLE,RUNNING,BLOCKED,WAITING,TIMED_WAITING,TERMINATED。

下面是Thread.java中相关属性的源代码:


private char name[];

/*
 * Thread ID
 */
private long tid;

/*
 * Native method
 */
private native void setPriority0(int newPriority);

/**
 * The minimum priority that a thread can have.
 */
public final static int MIN_PRIORITY = 1;

/**
 * The default priority that is assigned to a thread.
 */
public final static int NORM_PRIORITY = 5;

/**
 * The maximum priority that a thread can have.
 */
public final static int MAX_PRIORITY = 10;

/**
 * A thread state.  A thread can be in one of the following states:
 * <ul>
 * <li>{@link #NEW}<br>
 *     A thread that has not yet started is in this state.
 *     </li>
 * <li>{@link #RUNNABLE}<br>
 *     A thread executing in the Java virtual machine is in this state.
 *     </li>
 * <li>{@link #BLOCKED}<br>
 *     A thread that is blocked waiting for a monitor lock
 *     is in this state.
 *     </li>
 * <li>{@link #WAITING}<br>
 *     A thread that is waiting indefinitely for another thread to
 *     perform a particular action is in this state.
 *     </li>
 * <li>{@link #TIMED_WAITING}<br>
 *     A thread that is waiting for another thread to perform an action
 *     for up to a specified waiting time is in this state.
 *     </li>
 * <li>{@link #TERMINATED}<br>
 *     A thread that has exited is in this state.
 *     </li>
 * </ul>
 *
 * <p>
 * A thread can be in only one state at a given point in time.
 * These states are virtual machine states which do not reflect
 * any operating system thread states.
 *
 * @since   1.5
 * @see #getState
 */
public enum State {
    /**
     * Thread state for a thread which has not yet started.
     */
    NEW,

    /**
     * Thread state for a runnable thread.  A thread in the runnable
     * state is executing in the Java virtual machine but it may
     * be waiting for other resources from the operating system
     * such as processor.
     */
    RUNNABLE,

    /**
     * Thread state for a thread blocked waiting for a monitor lock.
     * A thread in the blocked state is waiting for a monitor lock
     * to enter a synchronized block/method or
     * reenter a synchronized block/method after calling
     * {@link Object#wait() Object.wait}.
     */
    BLOCKED,

    /**
     * Thread state for a waiting thread.
     * A thread is in the waiting state due to calling one of the
     * following methods:
     * <ul>
     *   <li>{@link Object#wait() Object.wait} with no timeout</li>
     *   <li>{@link #join() Thread.join} with no timeout</li>
     *   <li>{@link LockSupport#park() LockSupport.park}</li>
     * </ul>
     *
     * <p>A thread in the waiting state is waiting for another thread to
     * perform a particular action.
     *
     * For example, a thread that has called <tt>Object.wait()</tt>
     * on an object is waiting for another thread to call
     * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
     * that object. A thread that has called <tt>Thread.join()</tt>
     * is waiting for a specified thread to terminate.
     */
    WAITING,

    /**
     * Thread state for a waiting thread with a specified waiting time.
     * A thread is in the timed waiting state due to calling one of
     * the following methods with a specified positive waiting time:
     * <ul>
     *   <li>{@link #sleep Thread.sleep}</li>
     *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
     *   <li>{@link #join(long) Thread.join} with timeout</li>
     *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
     *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
     * </ul>
     */
    TIMED_WAITING,

    /**
     * Thread state for a terminated thread.
     * The thread has completed execution.
     */
    TERMINATED;
}

在上面截取的Thread类源代码中我们可以看到,线程的优先级是通过一个native方法来实现的。而线程的状态是通过一个枚举类来定义。

线程信息的获取和设置

通过实现Runnable接口来创建一个Calculator线程类。定义它的run()方法,在这个方法中我们通过Thread.currentThread().getName()方法来获取线程名称并打印线程名和乘法运算表。

public class Calculator implements Runnable {
    private int number;

    public Calculator(int number) {
        this.number = number;
    }

    public void run() {
        for (int i = 1; i <= 10; i++) {
            System.out.printf("%s: %d * %d = %d\n",
                    Thread.currentThread().getName(), i, number, i * number);
        }
    }
}

接下来我们在main方法中创建10个大小的线程数组,并新建10个线程,为双数线程指定最高优先级,为单数线程执行最低优先级。并执定线程名:“Thread i”。

Thread[] threads = new Thread[10];

for (int i = 0; i < 10; i++) {
    threads[i] = new Thread(new Calculator(i));
    if (i % 2 == 0) {
        threads[i].setPriority(Thread.MAX_PRIORITY);
    } else {
        threads[i].setPriority(Thread.MIN_PRIORITY);
    }
    threads[i].setName("Thread " + i);
}

接下来,我们创建一个日志文件“./data/log.txt”。首先把10个线程的初始状态打印到日志文件中,然后启动10个线程。循环等待所有线程进入结束状态,线程状态一旦发生变化会打印线程信息到日志文件中。

FileWriter fw = null;
PrintWriter pw = null;

try {
    fw = new FileWriter("./data/log.txt");
    pw = new PrintWriter(fw);

    for (int i = 0; i < 10; i++) {
        pw.println("Main: Status of the Thread " + i + " is " + threads[i].getState());
        states[i] = threads[i].getState();
    }

    for (int i = 0; i < 10; i++) {
        threads[i].start();
    }

    boolean finish = false;
    while (!finish) {
        for (int i = 0; i < 10; i++) {
            if (threads[i].getState() != states[i]) {
                writeThreadInfo(pw, threads[i], states[i]);
                states[i] = threads[i].getState();
            }
        }
        finish = true;
        for (int i = 0; i < 10; i++) {
            finish = finish && threads[i].getState() == Thread.State.TERMINATED;
        }
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (pw != null) {
        pw.close();
    }
    if (fw != null) {
        try {
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

打印线程信息,状态,优先级的方法:

public static void writeThreadInfo(PrintWriter pw, Thread thread, Thread.State state) {
    pw.printf("Main: %d : %s\n", thread.getId(), thread.getName());
    pw.printf("Main: Priority %d\n", thread.getPriority());
    pw.printf("Main: old state: %s\n", state);
    pw.printf("Main: new state: %s\n", thread.getState());
}

查看日志信息

所有线程初始状态:NEW

Main: Status of the Thread 0 is NEW
Main: Status of the Thread 1 is NEW
Main: Status of the Thread 2 is NEW
Main: Status of the Thread 3 is NEW
Main: Status of the Thread 4 is NEW
Main: Status of the Thread 5 is NEW
Main: Status of the Thread 6 is NEW
Main: Status of the Thread 7 is NEW
Main: Status of the Thread 8 is NEW
Main: Status of the Thread 9 is NEW

选取一个线程看一下状态信息:

Main: 9 : Thread 0
Main: Priority 10
Main: old state: NEW
Main: new state: RUNNABLE

Main: 9 : Thread 0
Main: Priority 10
Main: old state: RUNNABLE
Main: new state: BLOCKED

Main: 9 : Thread 0
Main: Priority 10
Main: old state: BLOCKED
Main: new state: RUNNABLE

Main: 9 : Thread 0
Main: Priority 10
Main: old state: RUNNABLE
Main: new state: TERMINATED

 

共有 人打赏支持
粉丝 20
博文 91
码字总数 83019
×
阿拉德大陆的魔法师
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: