Java并发编程-01-线程的创建和线程信息获取

来源:互联网 发布:powerdesigner ubuntu 编辑:程序博客网 时间:2024/06/05 02:46

一、创建线程的方式

1、继承Thread类,覆盖run方法

2、实现Runnable接口,创建Thread类的实例,通过构造方法实现

3、Runnable接口只有一个抽象的run方法,也就是说Runnable接口本身不支持多线程

public interface Runnable {    /**     * When an object implementing interface <code>Runnable</code> is used     * to create a thread, starting the thread causes the object's     * <code>run</code> method to be called in that separately executing     * thread.     * <p>     * The general contract of the method <code>run</code> is that it may     * take any action whatsoever.     *     * @see     java.lang.Thread#run()     */    public abstract void run();}

4、Runnable接口多线程的实现

查看Thread类的源代码,可以看到很多构造函数的参数是Runnable类或者Runnable的子类,即通过Thread类的构造方法类启动Runnable接口实现多线程

    /**     * Allocates a new {@code Thread} object. This constructor has the same     * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}     * {@code (null, target, gname)}, where {@code gname} is a newly generated     * name. Automatically generated names are of the form     * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.     *     * @param  target     *         the object whose {@code run} method is invoked when this thread     *         is started. If {@code null}, this classes {@code run} method does     *         nothing.     */    public Thread(Runnable target) {        init(null, target, "Thread-" + nextThreadNum(), 0);    }


5、Runnable接口的优势

  • 避免单继承的局限,一个类可以继承多个接口。
  • 适合于资源的共享
6、Thread类是Runnable接口的一个实现子类

二、线程信息的获取

id:保存了线程的唯一标识符 Name:线程名称

Priority:保存了线程的优先级,线程的优先级是从一到10,1是最低优先级,10是最高优先级。

status:线程的状态,java中线程有6个状态:new,runnable,blocked,waiting,time,waiting,terminated

测试代码:

线程类

package com.concurrent.threadManager;/** * 线程的创建和运行 *  * @author Nicholas * */public class Calculator implements Runnable {private int number;public Calculator(int number) {this.number = number;}@Overridepublic void run() {for (int i = 0; i <= 10; i++) {System.out.printf("%s : %d * %d = %d\n", Thread.currentThread().getName(), number, i, i * number);}}}

主方法:

package com.concurrent.threadManager;import java.io.FileWriter;import java.io.IOException;import java.io.PrintWriter;import java.lang.Thread.State;public class MainTest {/** * 对于实现了runnable接口的类来说,创建一个Thread对象并不会创建一个新的执行线程 同样的,调用他的run方法,也不会创建一个新的执行线程 * 只有调用他的start方法事,才会创建一个新的执行线程 *  * @param args */public void testCreateThread() {for (int j = 0; j <= 10; j++) {Calculator calculator = new Calculator(j);Thread thread = new Thread(calculator);thread.start();}}/** * id:保存了线程的唯一标识符 Name:线程名称 * Priority:保存了线程的优先级,线程的优先级是从一到10,1是最低优先级,10是最高优先级。 * status:线程的状态,java中线程有6个状态:new,runnable,blocked,waiting,time * waiting,terminated */public static void WriteThreadInfo(PrintWriter printWriter, Thread thread,State state) {printWriter.printf("Main : ID  %d - %s\n", thread.getId(),thread.getName());printWriter.printf("Main : Priority: %d\n", thread.getPriority());printWriter.printf("Main : Old status -%s\n", state);printWriter.printf("Main : New status -%s\n", thread.getState());printWriter.printf("Main : *******************************\n");}public static void main(String[] args) {Thread threads[] = new Thread[10];// 创建10个线程Thread.State status[] = new Thread.State[10];// 创建保存10个线程状态的数组// 创建10个Calculator对象数组,为每个对象都设置不同的数字,然后用他们作为thread构造器的参数,创建10个线程对象// 将偶数部分优先级设为最高,奇数的设置为最低for (int i = 0; i < 10; i++) {threads[i] = new Thread(new Calculator(i));if (i % 2 == 0) {threads[i].setName("高优先级  ---Thread -" + i);threads[i].setPriority(Thread.MAX_PRIORITY);} else {threads[i].setName("低优先级  ---Thread -" + i);threads[i].setPriority(Thread.MIN_PRIORITY);}}// 创建PrintWriter对象,把线程的演变保存到log文本中// 把10个线程的状态写入文件,现在线程的状态是NEWtry (FileWriter fileWriter = new FileWriter(".\\log.txt");PrintWriter printWriter = new PrintWriter(fileWriter);) {for (int i = 0; i < 10; i++) {printWriter.println("Main:Status of Thread " + i + " : "+ threads[i].getState());status[i] = threads[i].getState();}// 线程执行for (int i = 0; i < 10; i++) {threads[i].start();}// 把状态发生了变化的,写入到文件boolean finished = false;while (!finished) {for (int i = 0; i < 10; i++) {if (threads[i].getState() != status[i]) {WriteThreadInfo(printWriter, threads[i], status[i]);status[i] = threads[i].getState();}}finished = true;for (int i = 0; i < 10; i++) {finished = finished&& (threads[i].getState() == State.TERMINATED);}}} catch (IOException e) {e.printStackTrace();}}}

打印的log信息

Main:Status of Thread 0 : NEWMain:Status of Thread 1 : NEWMain:Status of Thread 2 : NEWMain:Status of Thread 3 : NEWMain:Status of Thread 4 : NEWMain:Status of Thread 5 : NEWMain:Status of Thread 6 : NEWMain:Status of Thread 7 : NEWMain:Status of Thread 8 : NEWMain:Status of Thread 9 : NEWMain : ID  10 - 高优先级  ---Thread -0Main : Priority: 10Main : Old status -NEWMain : New status -RUNNABLEMain : *******************************Main : ID  11 - 低优先级  ---Thread -1Main : Priority: 1Main : Old status -NEWMain : New status -BLOCKEDMain : *******************************Main : ID  12 - 高优先级  ---Thread -2Main : Priority: 10Main : Old status -NEWMain : New status -BLOCKEDMain : *******************************Main : ID  13 - 低优先级  ---Thread -3Main : Priority: 1Main : Old status -NEWMain : New status -BLOCKEDMain : *******************************Main : ID  14 - 高优先级  ---Thread -4Main : Priority: 10Main : Old status -NEWMain : New status -BLOCKEDMain : *******************************Main : ID  15 - 低优先级  ---Thread -5Main : Priority: 1Main : Old status -NEWMain : New status -BLOCKEDMain : *******************************Main : ID  16 - 高优先级  ---Thread -6Main : Priority: 10Main : Old status -NEWMain : New status -BLOCKEDMain : *******************************Main : ID  17 - 低优先级  ---Thread -7Main : Priority: 1Main : Old status -NEWMain : New status -BLOCKEDMain : *******************************Main : ID  18 - 高优先级  ---Thread -8Main : Priority: 10Main : Old status -NEWMain : New status -BLOCKEDMain : *******************************Main : ID  19 - 低优先级  ---Thread -9Main : Priority: 1Main : Old status -NEWMain : New status -BLOCKEDMain : *******************************Main : ID  10 - 高优先级  ---Thread -0Main : Priority: 10Main : Old status -RUNNABLEMain : New status -TERMINATEDMain : *******************************Main : ID  15 - 低优先级  ---Thread -5Main : Priority: 1Main : Old status -BLOCKEDMain : New status -RUNNABLEMain : *******************************Main : ID  17 - 低优先级  ---Thread -7Main : Priority: 1Main : Old status -BLOCKEDMain : New status -RUNNABLEMain : *******************************Main : ID  15 - 低优先级  ---Thread -5Main : Priority: 1Main : Old status -RUNNABLEMain : New status -TERMINATEDMain : *******************************Main : ID  17 - 低优先级  ---Thread -7Main : Priority: 1Main : Old status -RUNNABLEMain : New status -TERMINATEDMain : *******************************Main : ID  19 - 低优先级  ---Thread -9Main : Priority: 1Main : Old status -BLOCKEDMain : New status -RUNNABLEMain : *******************************Main : ID  19 - 低优先级  ---Thread -9Main : Priority: 1Main : Old status -RUNNABLEMain : New status -TERMINATEDMain : *******************************Main : ID  13 - 低优先级  ---Thread -3Main : Priority: 1Main : Old status -BLOCKEDMain : New status -RUNNABLEMain : *******************************Main : ID  13 - 低优先级  ---Thread -3Main : Priority: 1Main : Old status -RUNNABLEMain : New status -TERMINATEDMain : *******************************Main : ID  11 - 低优先级  ---Thread -1Main : Priority: 1Main : Old status -BLOCKEDMain : New status -RUNNABLEMain : *******************************Main : ID  18 - 高优先级  ---Thread -8Main : Priority: 10Main : Old status -BLOCKEDMain : New status -BLOCKEDMain : *******************************Main : ID  14 - 高优先级  ---Thread -4Main : Priority: 10Main : Old status -BLOCKEDMain : New status -BLOCKEDMain : *******************************Main : ID  12 - 高优先级  ---Thread -2Main : Priority: 10Main : Old status -BLOCKEDMain : New status -BLOCKEDMain : *******************************Main : ID  14 - 高优先级  ---Thread -4Main : Priority: 10Main : Old status -RUNNABLEMain : New status -BLOCKEDMain : *******************************Main : ID  18 - 高优先级  ---Thread -8Main : Priority: 10Main : Old status -BLOCKEDMain : New status -BLOCKEDMain : *******************************Main : ID  11 - 低优先级  ---Thread -1Main : Priority: 1Main : Old status -RUNNABLEMain : New status -BLOCKEDMain : *******************************Main : ID  16 - 高优先级  ---Thread -6Main : Priority: 10Main : Old status -BLOCKEDMain : New status -TERMINATEDMain : *******************************Main : ID  11 - 低优先级  ---Thread -1Main : Priority: 1Main : Old status -BLOCKEDMain : New status -RUNNABLEMain : *******************************Main : ID  14 - 高优先级  ---Thread -4Main : Priority: 10Main : Old status -BLOCKEDMain : New status -TERMINATEDMain : *******************************Main : ID  18 - 高优先级  ---Thread -8Main : Priority: 10Main : Old status -BLOCKEDMain : New status -TERMINATEDMain : *******************************Main : ID  12 - 高优先级  ---Thread -2Main : Priority: 10Main : Old status -BLOCKEDMain : New status -TERMINATEDMain : *******************************

可以看出

1、高优先级的线程比低有限级的线程结束的早

2、jvm使用线程的Priority属性来决定某一刻由那个线程来使用CPU。

3、如果setPriority设置的优先级不是1到10,就会抛出IllegalArgumentException异常


0 0