第七步:并发测试打开idea创建类:Counter1a.java,需要根据自己需求改装。
具体代码和操作如下:
package com.example.demo;
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);
}
}