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

本文介绍了Java中创建线程的两种主要方式:继承Thread类和实现Runnable接口,并阐述了Runnable接口的优势。同时,讲解了线程信息的获取,包括线程ID、名称、优先级和状态,以及线程状态的六个阶段。还提供了线程优先级的测试代码,指出高优先级线程并不总是先结束,线程的Priority属性用于决定CPU使用权限。
摘要由CSDN通过智能技术生成

一、创建线程的方式

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;
	}

	@Override
	public 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个线程的状态写入文件,现在线程的状态是NEW
		try (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 : NEW
Main:Status of Thread 1 : NEW
Main:Status of Thread 2 : NEW
Main:Status of Thread 3 : NEW
Main:Status of Thread 4 : NEW
Main:Status of Thread 5 : NEW
Main:Status of Thread 6 : NEW
Main:Status of Thread 7 : NEW
Main:Status of Thread 8 : NEW
Main:Status of Thread 9 : NEW
Main : ID  10 - 高优先级  ---Thread -0
Main : Priority: 10
Main : Old status -NEW
Main : New status -RUNNABLE
Main : *******************************
Main : ID  11 - 低优先级  ---Thread -1
Main : Priority: 1
Main : Old status -NEW
Main : New status -BLOCKED
Main : *******************************
Main : ID  12 - 高优先级  ---Thread -2
Main : Priority: 10
Main : Old status -NEW
Main : New status -BLOCKED
Main : *******************************
Main : ID  13 - 低优先级  ---Thread -3
Main : Priority: 1
Main : Old status -NEW
Main : New status -BLOCKED
Main : *******************************
Main : ID  14 - 高优先级  ---Thread -4
Main : Priority: 10
Main : Old status -NEW
Main : New status -BLOCKED
Main : *******************************
Main : ID  15 - 低优先级  ---Thread -5
Main : Priority: 1
Main : Old status -NEW
Main : New status -BLOCKED
Main : *******************************
Main : ID  16 - 高优先级  ---Thread -6
Main : Priority: 10
Main : Old status -NEW
Main : New status -BLOCKED
Main : *******************************
Main : ID  17 - 低优先级  ---Thread -7
Main : Priority: 1
Main : Old status -NEW
Main : New status -BLOCKED
Main : *******************************
Main : ID  18 - 高优先级  ---Thread -8
Main : Priority: 10
Main : Old status -NEW
Main : New status -BLOCKED
Main : *******************************
Main : ID  19 - 低优先级  ---Thread -9
Main : Priority: 1
Main : Old status -NEW
Main : New status -BLOCKED
Main : *******************************
Main : ID  10 - 高优先级  ---Thread -0
Main : Priority: 10
Main : Old status -RUNNABLE
Main : New status -TERMINATED
Main : *******************************
Main : ID  15 - 低优先级  ---Thread -5
Main : Priority: 1
Main : Old status -BLOCKED
Main : New status -RUNNABLE
Main : *******************************
Main : ID  17 - 低优先级  ---Thread -7
Main : Priority: 1
Main : Old status -BLOCKED
Main : New status -RUNNABLE
Main : *******************************
Main : ID  15 - 低优先级  ---Thread -5
Main : Priority: 1
Main : Old status -RUNNABLE
Main : New status -TERMINATED
Main : *******************************
Main : ID  17 - 低优先级  ---Thread -7
Main : Priority: 1
Main : Old status -RUNNABLE
Main : New status -TERMINATED
Main : *******************************
Main : ID  19 - 低优先级  ---Thread -9
Main : Priority: 1
Main : Old status -BLOCKED
Main : New status -RUNNABLE
Main : *******************************
Main : ID  19 - 低优先级  ---Thread -9
Main : Priority: 1
Main : Old status -RUNNABLE
Main : New status -TERMINATED
Main : *******************************
Main : ID  13 - 低优先级  ---Thread -3
Main : Priority: 1
Main : Old status -BLOCKED
Main : New status -RUNNABLE
Main : *******************************
Main : ID  13 - 低优先级  ---Thread -3
Main : Priority: 1
Main : Old status -RUNNABLE
Main : New status -TERMINATED
Main : *******************************
Main : ID  11 - 低优先级  ---Thread -1
Main : Priority: 1
Main : Old status -BLOCKED
Main : New status -RUNNABLE
Main : *******************************
Main : ID  18 - 高优先级  ---Thread -8
Main : Priority: 10
Main : Old status -BLOCKED
Main : New status -BLOCKED
Main : *******************************
Main : ID  14 - 高优先级  ---Thread -4
Main : Priority: 10
Main : Old status -BLOCKED
Main : New status -BLOCKED
Main : *******************************
Main : ID  12 - 高优先级  ---Thread -2
Main : Priority: 10
Main : Old status -BLOCKED
Main : New status -BLOCKED
Main : *******************************
Main : ID  14 - 高优先级  ---Thread -4
Main : Priority: 10
Main : Old status -RUNNABLE
Main : New status -BLOCKED
Main : *******************************
Main : ID  18 - 高优先级  ---Thread -8
Main : Priority: 10
Main : Old status -BLOCKED
Main : New status -BLOCKED
Main : *******************************
Main : ID  11 - 低优先级  ---Thread -1
Main : Priority: 1
Main : Old status -RUNNABLE
Main : New status -BLOCKED
Main : *******************************
Main : ID  16 - 高优先级  ---Thread -6
Main : Priority: 10
Main : Old status -BLOCKED
Main : New status -TERMINATED
Main : *******************************
Main : ID  11 - 低优先级  ---Thread -1
Main : Priority: 1
Main : Old status -BLOCKED
Main : New status -RUNNABLE
Main : *******************************
Main : ID  14 - 高优先级  ---Thread -4
Main : Priority: 10
Main : Old status -BLOCKED
Main : New status -TERMINATED
Main : *******************************
Main : ID  18 - 高优先级  ---Thread -8
Main : Priority: 10
Main : Old status -BLOCKED
Main : New status -TERMINATED
Main : *******************************
Main : ID  12 - 高优先级  ---Thread -2
Main : Priority: 10
Main : Old status -BLOCKED
Main : New status -TERMINATED
Main : *******************************

可以看出

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

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

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值