public class ThreadTest09 {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable3());
t.setName("t");
t.start();
try {
Thread.sleep(1000 * 5);
} catch (InterruptedException e) {
e.printStackTrace();
}
//5s后杀死进程
t.stop(); //已弃用
}
}
class MyRunnable3 implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "————>begin");
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "————>" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "————>over");
}
}
public class ThreadTest10 {
public static void main(String[] args) {
MyRunnable4 run4 = new MyRunnable4();
Thread t = new Thread(run4);
t.setName("t");
t.start();
try {
Thread.sleep(1000 * 5);
} catch (InterruptedException e) {
e.printStackTrace();
}
//5s后终止线程
//想什么时候终止线程,只需把标记改为false即可
run4.run = false;
}
}
class MyRunnable4 implements Runnable{
boolean run = true; //设立一个布尔标记
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if (run){
System.out.println(Thread.currentThread().getName() + "————>" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
//在结束之前可以保存
//save....
return;
}
}
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- oldu.cn 版权所有 浙ICP备2024123271号-1
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务