文档章节

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

阿拉德大陆的魔法师
 阿拉德大陆的魔法师
发布于 2016/11/21 12:01
字数 1288
阅读 36
收藏 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

 

© 著作权归作者所有

共有 人打赏支持
阿拉德大陆的魔法师
粉丝 25
博文 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面试:投行的15个多线程和并发面试题

本文由ImportNew -一杯哈希不加盐 翻译自dzone。欢迎加入翻译小组。转载请见文末要求。 多线程和并发问题已成为各种 Java 面试中必不可少的一部分。如果你准备参加投行的 Java 开发岗位面试,...

ImportNew
08/23
0
0
读书笔记之《Java并发编程的艺术》-并发编程基础

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

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

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

LCZ777
2014/05/27
0
0
基于JVM原理、JMM模型和CPU缓存模型深入理解Java并发编程

许多以Java多线程开发为主题的技术书籍,都会把对Java虚拟机和Java内存模型的讲解,作为讲授Java并发编程开发的主要内容,有的还深入到计算机系统的内存、CPU、缓存等予以说明。实际上,在实...

leoliu168
11/08
0
0

没有更多内容

加载失败,请刷新页面

加载更多

Libusb交叉编译和移植

  Libusb交叉编译和移植      某项目内核需要支持USB的相关操作,所以考虑移植Libusb库      1、到官网下载最新的libusb源码(1.0.22)      2、解压源码      3、进入解压...

SEOwhywhy
2分钟前
0
0
阿里云HBase全新发布X-Pack NoSQL数据库再上新台阶

一、八年双十一,造就国内最大最专业HBase技术团队 阿里巴巴集团早在2010开始研究并把HBase投入生产环境使用,从最初的淘宝历史交易记录,到蚂蚁安全风控数据存储。持续8年的投入,历经8年双...

阿里云云栖社区
5分钟前
0
0
【58沈剑 架构师之路】数据库索引,到底是什么做的?

问题1. 数据库为什么要设计索引? 图书馆存了1000W本图书,要从中找到《架构师之路》,一本本查,要查到什么时候去? 于是,图书管理员设计了一套规则: (1)一楼放历史类,二楼放文学类,三楼...

张锦飞
5分钟前
0
0
android webpage err_unknown_url_scheme

搞一个 Android 的webview demo 来访问网页, 结果 模拟器就报错了: webpage err_unknown_url_scheme 于是去百度了 一下。发现挺多解决方案的,都拿来试试。居然有几种方式都可以。 1, 参考...

之渊
8分钟前
0
0
JVM总结

区域简介 JVM运行时区域有些随着虚拟机进程的启动而存在,有些依赖于用户线程的启动和结束而建立和销毁,大致分为以下几类:方法区,虚拟机栈,本地方法栈,堆,程序计数器,概念图如下(源于...

瑞查德-Jack
9分钟前
0
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部