如何正确终止一个线程的执行
方法:设置一个布尔类型的控制因子,使用它来标记状态停止的线程。
package 多线程;
/*
* 怎么合理的终止一个线程的执行,这种方式很常用。
*/
public class ThreadTest09 {
public static void main(String[] args) {
MyRunnable4 r = new MyRunnable4();
Thread t = new Thread(r);
t.setName("tt");
t.start();
//主线程睡眠5秒;
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//终止线程
//什么时候想终止t的执行,就把标记修改为false,就结束了。
r.run = false;
}
}
class MyRunnable4 implements Runnable{
//打一个布尔标记
boolean run = true;
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
//return 就结束了,你在结束之前还有什么每保存的,在这里可以保存。
//终止当前线程
return;
}
}
}
}
注意:t.stop()这种方式能够强行终止线程,但是存在很大的风险:它直接将线程杀死,没有保存的数据容易丢失。
1.5 线程的同步(加锁)
线程同步,指某一时刻只允许一个线程来访问共享资源,线程同步其实是对对象加锁;
package 多线程;
public class Thread10 {
public static void main(String[] args) {
MyThread10 mt = new MyThread10();
Thread t1 = new Thread(mt);
t1.setName("aa");
t1.start();
Thread t2 = new Thread(mt);
t2.setName("bb");
t2.start();
}
}
class MyThread10 extends Thread{
private int ss = 0;
public void run() {
//线程同步机制
synchronized(this) {
for(int i = 0; i < 10 ; i ++) {
ss += i;
}
System.out.println(Thread.currentThread().getName()+", ss = "+ ss);
ss = 0;
}
}
}
同步的代码越多,执行的时间就会越长,其他线程等待的时间就会越长,影响效率,因此,优先考虑同步代码块。
守护线程:
package 多线程;
/*
*
* 守护线程:
所有的用户线程结束生命周期,守护线程才会结束生命周期,只要有一个用户线程存在,那么
守护线程就不会结束;
* 用户线程! 主线程执行结束了,但用户线程仍然将数据打印出来了。
*/
public class Thread13 {
public static void main(String[] args) {
Thread t = new Thread( new MyThread13());
t.setDaemon(true);
System.out.println(t.isDaemon());
t.start();
for(int j = 0 ; j <= 24; j++) {
System.out.println(Thread.currentThread().getName()+"----> "+j);
}
}
}
class MyThread13 implements Runnable{
public void run() {
for(int i = 0 ; i <= 24; i++) {
System.out.println(Thread.currentThread().getName()+"----> "+i);
}
}
}