黑马程序员--多线程(三)之线程停止

---------------------- android培训java培训、期待与您交流! ----------------------

   线程停止:

 run方法结束就可以停止线程。

开启多线程通常代码都是循环结构,只要控制住循环就可以结束run方法,即结束线程。

特殊情况:当线程处于冻结状态(wait 、sleep...),就不会读取到标记,就无法结束线程。

这是需要对冻结线程进行清除。强制是线程恢复到运行状态,这样就可以操作标记线程城结束。Thread类提供了interrupt方法。

首先看一段线程冻结状态的代码:

class StopThreadDemo {
	public static void main(String[] args) {
		StopThread st = new StopThread();

		Thread t1 = new Thread(st);
		Thread t2 = new Thread(st);
		t1.start();
		t2.start();

		int num = 0;
		while (true) {
			if (num++ == 50) {
				st.changeFlag();
				break;
			}
			System.out.println(Thread.currentThread().getName()+
"-->"+num);
		}
	}
}

class StopThread implements Runnable {
	private boolean flag = true;

	public synchronized void run() {
		while (flag) {
			try {
				this.wait();//线程0或者线程1进来之后,都处于冻结状态
			} catch (InterruptedException e) {
				
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + "-->run");
		}
	}

	public void changeFlag() {
		flag = false;
	}
}


 

以上改程序演示的是主线程结束后,线程0和线程1都处于冻结状态。

想使这两个冻结线程结束可以使用interrupt方法来中断冻结线程,此时会抛出异常。并对异常进行处理是其结束。

代码如下:

class StopThreadDemo {
	public static void main(String[] args) {
		StopThread st = new StopThread();

		Thread t1 = new Thread(st);
		Thread t2 = new Thread(st);
		t1.start();
		t2.start();

		int num = 0;
		while (true) {
			if (num++ == 50) {
				st.changeFlag();
				t1.interrupt();
				t2.interrupt();
				break;
			}
			System.out.println(Thread.currentThread().getName() + "-->"+num);
		}
	}
}

class StopThread implements Runnable {
	private boolean flag = true;

	public synchronized void run() {
		while (flag) {
			try {
				this.wait();//线程0或者线程1进来之后,都处于冻结状态
			} catch (InterruptedException e) {
	flag = false;		
			}
			System.out.println(Thread.currentThread().getName() + "-->run");
		}
	}

	public void changeFlag() {
		flag = false;
	}
}


 

setDaemon(boolean on)

将该线程标记为守护线程或用户线程。当正在运行的线程都是守护线程时,Java 虚拟机退出。 该方法必须在启动线程前调用。当主线程结束后该线程自动结束。

Join方法

当线程A执行到线程B的join方法时,A就会等待,等B线程结束后A再继续

执行。Join可以用来临时假如线程执行。

线程的技巧性写法示例:

public class Demo {
	public static void main(String[] args) {
		new Thread() {
			public void run() {
				for(int i=0;i<100;i++) 
					System.out.println("Thread-->i="+i);
			}
		}.start();

		Runnable r = new Runnable(){
			public void run() {
				for(int i=0;i<100;i++) 
					System.out.println("Runnable-->i+"+i);
			}
		}; 
		new Thread(r).start();
	}
}
//该写法用的是匿名类。


 

---------------------- android培训java培训、期待与您交流! ---------------------- 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值