//下面代码是在5秒后终止线程,通过一个实现Runnable接口的类的对象的成员变量控制线程的运行,见代码:
package ThreadTest;
class Processor08 implements Runnable{
public boolean flag = true;
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0; i<10; i++){
if(flag){
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(Thread.currentThread().getName() + "-->" + i);
}
else
return;
}
}
}
public class ThreadTest08 {
public static void main(String[] args) throws Exception{
Processor08 p = new Processor08();
Thread t = new Thread(p);
t.setName("t");
t.start();
Thread.sleep(5000);
p.flag = false;
}
}