java 多线程基础之一:多线程创建,执行,状态管理

摘要: 这几天在看一本书:<Java 7 Concurrency Cookbook> 因为是纯英文版,平时也很少有时间专门去看,快到年底了,没心情做事,所以看看,顺便复习下多线程编程所以,就记录下来

这几天在看一本书: 因为是纯英文版,平时也很少有时间专门去看,快到年底了,没心情做事,所以看看,顺便复习下多线程编程所以,就记录下来。

创建和运行一个线程 有两种方法创建一个线程:
1. 继承 Thread 类 重载 Override run() 方法
2. 创建一个类实现 Runnable 接口,然后创建一个Thread类,用 实现Runnable 接口的类的实例作为参数.

一个实例如下:

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(),number,i,i*number);
		}
	}
	
	public static void main(String[] args) {
		for (int i=1; i<=10; i++){
			Calculator calculator=new Calculator(i);
			Thread thread=new Thread(calculator);
			thread.start();
		}
	}
}



线程的启动必须用start() 方法,而不是run(),如果调用run()方法,跟普通方法没什么差别,只有用start()方法才能启动线程.

结果类似如下:
Thread-3: 4 * 10 = 40
Thread-7: 8 * 4 = 32
Thread-7: 8 * 5 = 40
Thread-7: 8 * 6 = 48
Thread-7: 8 * 7 = 56
Thread-7: 8 * 8 = 64
Thread-7: 8 * 9 = 72
Thread-7: 8 * 10 = 80
Thread-0: 1 * 7 = 7
Thread-0: 1 * 8 = 8
Thread-0: 1 * 9 = 9
Thread-0: 1 * 10 = 10


得到线程的相关信息,设置线程的相关信息
线程中的一些属性能够帮助我们确定是哪一个线程,知道线程的状态,以及优先级等,常用的属性如下:
ID: 每一个线程都有一个独立的ID,不会重复。
Name: 线程的名字
Priority:线程的优先级,优先级只能在 1 到 10 之间,其他都是非法的。10 是最高的优先级,1是最低的。一般情况下不需要设置线程的优先级,也许在有的情况下可以用到。
Status:线程的状态,有如下几种状态:new,runnable,blocked,waiting,time waiting,terminated


import java.lang.Thread.State;

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(),number,i,i*number);
		}
	}
	
	public static void main(String[] args) {
		System.out.printf("Minimum Priority: %s\n",Thread.MIN_PRIORITY);
		System.out.printf("Normal Priority: %s\n",Thread.NORM_PRIORITY);
		System.out.printf("Maximun Priority: %s\n",Thread.MAX_PRIORITY);
		
		Thread threads[];
		Thread.State status[];
		
		//发起10个线程,5个最高优先级,5个最低优先级,并设定线程的名字
		threads=new Thread[10];
		status=new Thread.State[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+"线程");
		}
		
		
		// Wait for the finalization of the threads. Meanwhile, 
		// write the status of those threads in a file
		
		try {
			
			for (int i=0; i<10; i++){
				System.out.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 finish=false;
			while (!finish) {
				for (int i=0; i<10; i++){
					if (threads[i].getState()!=status[i]) {
						writeThreadInfo(threads[i],status[i]);
						status[i]=threads[i].getState();
					}
				}
				
				finish=true;
				for (int i=0; i<10; i++){
					finish=finish &&(threads[i].getState()==State.TERMINATED);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 *  打印线程状态
	 * @param thread : Thread 
	 * @param state : Old state of the thread
	 */
	private static void writeThreadInfo(Thread thread, State state) {
		System.out.printf("Main : Id %d - %s\n",thread.getId(),thread.getName());
		System.out.printf("Main : Priority: %d\n",thread.getPriority());
		System.out.printf("Main : Old State: %s\n",state);
		System.out.printf("Main : New State: %s\n",thread.getState());
		System.out.println("Main : ************************************\n");
	}
}


这样就能设置线程的属性,以及的倒线程的属性. 可以看到结果如下:
Main : Old State: BLOCKED
Main : New State: BLOCKED
Main : ************************************

Thread 5线程: 5 * 9 = 45
Thread 5线程: 5 * 10 = 50
Main : Id 13 - Thread 5线程
Main : Priority: 1
Main : Old State: BLOCKED
Main : New State: TERMINATED
Main : ************************************


下一篇将继续讲线程的中断处理,以及异常处理.

上一篇: 浓雾密布的京城-《沁园春.雾》
下一篇: java 多线程基础之二:线程的中断(interrupt)
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号