- 相關(guān)推薦
Java優(yōu)先級線(xiàn)程代碼示例
使用過(guò)Bit下載軟件的同學(xué)應該很清楚,我們有多個(gè)下載任務(wù)同時(shí)執行,而其中的某一個(gè)或多個(gè)是非常重要的,于是給這些任務(wù)設定一個(gè)高度優(yōu)先,以便任務(wù)可以獲取更多的帶寬盡早完成下載。Java線(xiàn)程的優(yōu)先級也差不多,優(yōu)先級越高排程器就會(huì )給它越多的CPU執行時(shí)間,但請注意:如果有多個(gè)線(xiàn)程在等待一個(gè)機鎖的時(shí)候,并不是優(yōu)先級越高就可以越早執行。
復制代碼 代碼如下:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* 線(xiàn)程的優(yōu)先級
* 10個(gè)計數器線(xiàn)程分別被設置了不同的優(yōu)先級,我們通過(guò)計數器的累加來(lái)觀(guān)察優(yōu)先級的作用
* @author 五斗米
* @blog http://blog.csdn.net/mq612
*/
public class TestMain extends JFrame {
private MyThread [] thread = null; // 要操作的線(xiàn)程
private JPanel pane = null;
private JButton startButton = null, stopButton = null; // 啟動(dòng)、結束按鈕
public TestMain(){
super("線(xiàn)程的優(yōu)先級");
pane = new JPanel();
thread = new MyThread[10];
for(int i = 0; i < 10; i++){ // 線(xiàn)程的優(yōu)先級最小是1,最大是10
thread[i] = new MyThread(i + 1);
}
startButton = new JButton("執行");
startButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < 10; i++){
thread[i].start();
}
}
});
stopButton = new JButton("結束");
stopButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < 10; i++){
thread[i].quit();
}
}
});
JPanel p = new JPanel();
p.add(startButton);
p.add(stopButton);
this.getContentPane().add(pane);
this.getContentPane().add(p, BorderLayout.NORTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 300);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
/**
* 計數器線(xiàn)程
*/
class MyThread extends Thread{
private JTextField text = null; // 計數器
private int i = 0; // 計數器
private int priority = 0; // 優(yōu)先級
private JLabel label = null; // 優(yōu)先級顯示標簽
private boolean b = true; // 控制線(xiàn)程結束的boolean變量
public MyThread(int priority){
this.priority = priority;
this.setPriority(priority);
JPanel p = new JPanel();
label = new JLabel("Priority=" + priority);
text = new JTextField(12);
p.add(label);
p.add(text);
pane.add(p); // 將自己的計數器加入主窗口面板中
}
/**
* 結束線(xiàn)程
*/
public void quit(){
b = false;
}
public void run(){
while(b){
this.text.setText(Integer.toString(i++));
try {
this.sleep(1); // 減小這里的毫秒數,可以讓我們更容易觀(guān)察到結果
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
public static void main(String [] args){
new TestMain();
}
}
【Java優(yōu)先級線(xiàn)程代碼示例】相關(guān)文章:
Java線(xiàn)程同步的優(yōu)先級介紹04-10
Java線(xiàn)程同步的優(yōu)先級是什么04-24
關(guān)于循環(huán)的java代碼示例05-28
java中通用的線(xiàn)程池實(shí)例代碼08-27
java構造函數實(shí)現代碼示例04-01
java的多線(xiàn)程04-09
java多線(xiàn)程05-11