AWT實現多線程
一個簡單的多線程例子,由AWT實現,兩個按鈕,點擊第一個,開始自加,點擊第二個按鈕時結束,代碼如下。
import java.awt.*; import java.awt.event.*; class StopableFrame extends Frame implements Runnable, ActionListener{ static long i = 0; static Label lab = new Label(); Button but1 = new Button("Start"); Button but2 = new Button("Stop"); static boolean running = false; public void actionPerformed(ActionEvent e){ if(e.getActionCommand().equals("Start")){ new Thread(new StopableFrame(), "Start").start(); }else{ Thread t = new Thread(new StopableFrame(), "Stop"); t.setPriority(10); t.start(); } } public StopableFrame(){ super(); } public void exec(){ but1.addActionListener(this); but2.addActionListener(this); add(lab); add(but1); add(but2); setLayout(new GridLayout()); setSize(300, 100); setVisible(true); } public StopableFrame(String name){ super(name); } public void run(){ if(Thread.currentThread().getName().equals("Start")){ if(running){ System.out.println("Process is running!!"); }else{ running = true; while(running){ lab.setText(Long.toString(i++)); } } }else{ running = false; lab.setText(lab.getText() + "----Stoped !!!"); } } } public class AWTThreadDemo{ public static void main(String[] args){ StopableFrame sf = new StopableFrame("Stopable Frame"); sf.exec(); } }