使用過Bit下載軟件的同學應該很清楚,我們有多個下載任務同時執行,而其中的某一個或多個是非常重要的,於是給這些任務設定一個高度優先,以便任務可以獲取更多的帶寬儘早完成下載。Java線程的'優先級也差不多,優先級越高排程器就會給它越多的CPU執行時間,但請注意:如果有多個線程在等待一個機鎖的時候,並不是優先級越高就可以越早執行。
複製代碼 代碼如下:
import erLayout;
import onEvent;
import onListener;
import ton;
import me;
import el;
import el;
import tField;
/**
* 線程的優先級
* 10個計數器線程分別被設置了不同的優先級,我們通過計數器的累加來觀察優先級的作用
* @author 五斗米
* @blog
*/
public class TestMain extends JFrame {
private MyThread [] thread = null; // 要操作的線程
private JPanel pane = null;
private JButton startButton = null, stopButton = null; // 啓動、結束按鈕
public TestMain(){
super("線程的優先級");
pane = new JPanel();
thread = new MyThread[10];
for(int i = 0; i < 10; i++){ // 線程的優先級最小是1,最大是10
thread[i] = new MyThread(i + 1);
}
startButton = new JButton("執行");
ctionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < 10; i++){
thread[i]t();
}
}
});
stopButton = new JButton("結束");
ctionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < 10; i++){
thread[i]();
}
}
});
JPanel p = new JPanel();
(startButton);
(stopButton);
ontentPane()(pane);
ontentPane()(p, H);
efaultCloseOperation(_ON_CLOSE);
ize(500, 300);
ocationRelativeTo(null);
isible(true);
}
/**
* 計數器線程
*/
class MyThread extends Thread{
private JTextField text = null; // 計數器
private int i = 0; // 計數器
private int priority = 0; // 優先級
private JLabel label = null; // 優先級顯示標籤
private boolean b = true; // 控制線程結束的boolean變量
public MyThread(int priority){
rity = priority;
riority(priority);
JPanel p = new JPanel();
label = new JLabel("Priority=" + priority);
text = new JTextField(12);
(label);
(text);
(p); // 將自己的計數器加入主窗口面板中
}
/**
* 結束線程
*/
public void quit(){
b = false;
}
public void run(){
while(b){
ext(ring(i++));
try {
p(1); // 減小這裏的毫秒數,可以讓我們更容易觀察到結果
} catch (InterruptedException ex) {
tStackTrace();
}
}
}
}
public static void main(String [] args){
new TestMain();
}
}