java多线程测试
import java.awt.*; import java.awt.event.*; import java.applet.*; public class Counter1a extends Applet implements Runnable{ private int count = 0; private Button onOff = new Button("Toggle"); private Button start = new Button("Start"); private TextField t = new TextField(10); private boolean runFlag = true; private long i = 0; Thread athread;//define a thread public void init() { start.addActionListener(new StartL()); add(start); onOff.addActionListener(new OnOffL()); add(onOff); } public void run() { System.out.println("已经调用run()方法"); while(true) { try { athread.sleep(3000); }catch(InterruptedException e) { } if(runFlag) { count++; System.out.println("count = " + count); } } } class StartL implements ActionListener { public void actionPerformed(ActionEvent e) { Counter1a aCounter1a = new Counter1a(); athread = new Thread(aCounter1a);//process create athread.start(); System.out.println("已经按下start按钮"); } } class OnOffL implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("已经按下onOff按钮"); } } public static void main(String[] args) { Counter1a applet = new Counter1a(); Frame aFrame = new Frame("Counter1a"); aFrame.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) { System.exit(0); } }); aFrame.add(applet,BorderLayout.CENTER); aFrame.setSize(300,200); applet.init(); applet.start(); aFrame.setVisible(true); } }
Thread类 java的线程是通过java.lang.Thread类来实现的。Thread类中综合java程序中一个线程需要拥有的属性和方法。当我们生成一个Thread类的对象之后,一个新的线程就产生了