文档章节

Java并发编程初级篇(二):Java线程基本信息

阿拉德大陆的魔法师
 阿拉德大陆的魔法师
发布于 2016/11/21 12:01
字数 1288
阅读 30
收藏 0

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

 

© 著作权归作者所有

共有 人打赏支持
阿拉德大陆的魔法师
粉丝 22
博文 91
码字总数 83019
作品 0
西城
程序员
读书笔记之《Java并发编程的艺术》-并发编程容器和框架(重要)

读书笔记部分内容来源书出版书,版权归本书作者,如有错误,请指正。 欢迎star、fork,读书笔记系列会同步更新 git https://github.com/xuminwlt/j360-jdk module j360-jdk-thread/me.j360....

Hi徐敏
2015/11/11
0
1
跳槽时,这些Java面试题99%会被问到

我在 Oracle 已经工作了近 7 年,面试过从初级到非常资深的Java工程师,且由于 Java 组工作任务的特点,我非常注重面试者的计算机科学基础和编程语言的理解深度,可以不要求面试者非要精通 ...

Java小铺
08/15
0
0
读书笔记之《Java并发编程的艺术》-线程池和Executor的子孙们

读书笔记部分内容来源书出版书,版权归本书作者,如有错误,请指正。 欢迎star、fork,读书笔记系列会同步更新 git https://github.com/xuminwlt/j360-jdk module j360-jdk-thread/me.j360....

Hi徐敏
2015/11/11
0
1
【转】15个顶级Java多线程面试题及回答

Java 线程面试问题   在任何Java面试当中多线程和并发方面的问题都是必不可少的一部分。如果你想获得任何股票投资银行的前台资讯职位,那么你应该准备很多关于多线程的问题。在投资银行业务...

一只死笨死笨的猪
2014/09/30
0
0
读书笔记之《Java并发编程的艺术》-并发编程基础

读书笔记部分内容来源书出版书,版权归本书作者,如有错误,请指正。 欢迎star、fork,读书笔记系列会同步更新 git https://github.com/xuminwlt/j360-jdk module j360-jdk-thread/me.j360....

Hi徐敏
2015/11/11
0
8

没有更多内容

加载失败,请刷新页面

加载更多

下一页

最全最强解析:支付宝钱包系统架构内部剖析(架构图)

支付宝系统架构概况 典型处理默认 资金处理平台 财务会计 支付清算 核算中心 交易 柔性事务 支付宝的开源分布式消息中间件–Metamorphosis(MetaQ) Metamorphosis (MetaQ) 是一个高性能、高可...

晨猫
31分钟前
4
0
竞品分析

那什么样的场景需要用关键纬度分析法分析竞品呢? 竞品分析的目的是为了看竞品们和自己产品重合的业务都具备哪些功能点,以及这些功能是怎么做的,以此确定自己产品的优化方向。 竞品们的业务...

于谦老师
39分钟前
1
0
OSChina 周三乱弹 —— 公司女同事约我

Osc乱弹歌单(2018)请戳(这里) 【今日歌曲】 @莱布妮子:分享水木年华的单曲《蝴蝶花(2002年大提琴版)》 《蝴蝶花(2002年大提琴版)》- 水木年华 手机党少年们想听歌,请使劲儿戳(这里) ...

小小编辑
今天
1K
16
Linux环境搭建 | VMware下共享文件夹的实现

在进行程序开发的过程中,我们经常要在主机与虚拟机之间传递文件,比如说,源代码位于虚拟机,而在主机下阅读或修改源代码,这里就需要使用到 「共享文件」 这个机制了。本文介绍了两种共享文...

良许Linux
今天
9
0
JUC锁框架——AQS源码分析

JUC锁介绍 Java的并发框架JUC(java.util.concurrent)中锁是最重要的一个工具。因为锁,才能实现正确的并发访问。而AbstractQueuedSynchronizer(AQS)是一个用来构建锁和同步器的框架,使用A...

长头发-dawn
今天
5
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部