Java多线程知识点总结,超详细代码!(二)

如何正确终止一个线程的执行

方法:设置一个布尔类型的控制因子,使用它来标记状态停止的线程。

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);
		}
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值