每個執行續都有各自的優先順序,預設情況下,新增的執行續與建立該新增的執行續優先順序相同。

透過以下實驗可以修改執行續的優先權,為了方便觀察,製作一個ThreadBuilder hreadBuilder 建立多個執行續供修改設定。

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package ModifyThreadPriority;

import java.util.ArrayList;
import java.util.List;

public class ThreadBuilder {
	private List<Thread> threads = null;
	private class UnitThread implements Runnable{

		private static final int RUN_COUNT = 60; 
		private String name;
		public UnitThread(String name) {
			// TODO Auto-generated constructor stub
			this.name = name;
		}
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			int id = 0;
			
			while(id < RUN_COUNT) {
				id++;
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}

	public ThreadBuilder(int count) {
		threads = new ArrayList<Thread>();
		
		for(int i=0;i<count ;i++) {
			Thread thread = new Thread(new UnitThread("thread " + i));
			thread.start();
			getThreads().add(thread);
		}
	}

	public List<Thread> getThreads() {
		return threads;
	}
}

 

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package ModifyThreadPriority;

import java.util.Scanner;

public class ThreadPriorityTest {
	
	private static Thread[] getThreads() {
		ThreadGroup group = Thread.currentThread().getThreadGroup();
		Thread[] threads = new Thread[group.activeCount()];
		group.enumerate(threads);
		
		return threads;
	}
	
	private static void showThreadsPriority() {
		Thread[] threads = getThreads();
		
		System.out.println("*****************執行續*****************");
		System.out.println("ID\tName\tPriority");
		for(Thread thread : threads)
			System.out.println(thread.getId() + "\t" + thread.getName() + "\t" + thread.getPriority());
		System.out.println("**************************************");
		
	}
	
	private static void modifyPriority(int id,int priorityValue) {
		Thread[] threads = getThreads();
		
		for(Thread thread : threads) 
			if(thread.getId() == id)
				thread.setPriority(priorityValue);
	}
	
	public static void main(String[] args) {
		
		ThreadBuilder threadBuilder = new ThreadBuilder(10);
		
		Scanner scanner = new Scanner(System.in);
		showThreadsPriority();
		
		System.out.print("請輸入欲修改之執行續 ID ( 若離開程式請輸入 -1 )");
		int id = scanner.nextInt();
		while(id > 0) {
			System.out.print("請輸入修改的優先順序(1~10)");
			int priorityValue = scanner.nextInt();
			modifyPriority(id, priorityValue);
			
			showThreadsPriority();	
			System.out.println("請輸入欲修改之執行續 ID ");
			id = scanner.nextInt();
		}
		
		System.out.println("Done.");
	}
}

 

實驗結果如下:

 

完整專案(連結)

文章標籤
全站熱搜
創作者介紹
創作者 Lung-Yu,Tsai 的頭像
Lung-Yu,Tsai

Lung-Yu,Tsai 的部落格

Lung-Yu,Tsai 發表在 痞客邦 留言(0) 人氣(9)