實作Runnable界面,可以使用Thread 執行緒,透過(Thread).start(); 會進入run()方法
run()等同於第二個main、第二個虛擬CPU,可以在內部同時執行兩個程式,達到多工的效果
補充class Init: 按我
import java.awt.*;
import java.awt.event.*;
public class c001 extends Frame implements Runnable{
/*variable*/
Thread th1=null;
int x=0;
Button bt=null;
c001(){
Init.InitWin(this);
Init.addWinListen(this);
th1 = new Thread(this);
th1.start();
bt = new Button("Start");
Init.setButton(bt, 80, 40, 100, 50);
this.add(bt);
/*event*/
bt.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e) {
bt.setLabel("["+String.valueOf(x)+"]");
}
}
);
}
/*main*/
public static void main(String[] args){
c001 mm = new c001();
}
/*Override*/
/*run*/
public void run() {
while(true){
x = (x+1) % 10000;
}
}
}
此程式是每次按按鈕都會抓取不同的x值,而x在run()中每1/1000秒就加1,%10000是讓它不超過10000
請先 登入 以發表留言。