题目描述:线程10秒后停止,期间每个一秒打印学生是谁在听课。
package Calculator;
import java.lang.*;
public class ThreadTest{
public static void main(String[] args) throws Exception {
Learn learn=new Learn("小明");
learn.start();
Thread.sleep(10000);
learn.stopLearn();
}
}
class Learn extends Thread{
public Learn(String sName) {
super(sName);
}
public volatile static boolean exit=false;
@Override
public void run() {
int i=1;
while(!exit) {
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.getName()+"正在听课"+i);
i++;
}
super.run();
}
public void stopLearn() {
exit=true;
}
}
运行结果如下: