码迷,mamicode.com
首页 > 编程语言 > 详细

从头认识多线程-1.9 迫使线程停止的方法-return法

时间:2017-08-06 22:59:28      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:into   ted   主线程   sys   这一   extends   java   github   array   

这一章节我们来讨论一下还有一种停止线程的方法-return

1.在主线程上面return,是把全部在执行的线程都停掉

package com.ray.deepintothread.ch01.topic_9;

public class StopByReturn {
	public static void main(String[] args) throws InterruptedException {
		ThreadFive threadFive = new ThreadFive();
		Thread thread1 = new Thread(threadFive);
		thread1.start();
		Thread thread2 = new Thread(threadFive);
		thread2.start();
		Thread.sleep(200);
		return;
	}
}

class ThreadFive implements Runnable {

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName() + " begin");
		try {
			System.out.println(Thread.currentThread().getName() + " working");
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			System.out.println(Thread.currentThread().getName() + " exit");
		}
	}
}

输出:

Thread-1 begin
Thread-1 working
Thread-0 begin
Thread-0 working


2.在当前线程return,仅仅是单纯的停止当前线程

package com.ray.deepintothread.ch01.topic_9;

public class StopByReturn2 {
	public static void main(String[] args) throws InterruptedException {
		ThreadOne threadOne = new ThreadOne();
		threadOne.start();
		Thread.sleep(200);
		threadOne.interrupt();
	}
}

class ThreadOne extends Thread {

	@Override
	public void run() {
		while (true) {
			if (this.isInterrupted()) {
				System.out.println("return");
				return;
			}
		}
	}
}

输出:

return


package com.ray.deepintothread.ch01.topic_9;

import java.util.ArrayList;

public class StopByReturn3 {
	public static void main(String[] args) throws InterruptedException {
		ThreadOne threadTwo = new ThreadOne();
		ArrayList<Thread> list = new ArrayList<>();
		for (int i = 0; i < 3; i++) {
			Thread thread = new Thread(threadTwo);
			thread.start();
			list.add(thread);
		}
		Thread.sleep(20);
		list.get(0).interrupt();
	}
}

class ThreadTwo implements Runnable {

	@Override
	public void run() {
		while (true) {
			if (Thread.currentThread().isInterrupted()) {
				System.out.println("Thread name:" + Thread.currentThread().getName() + " return");
				return;
			}
		}
	}
}

输出:

Thread name:Thread-0 return

(然后其它线程一直在执行)


总结:这一章节我们讨论了一下return的两个方面,大家须要特别注意一点的就是return在main里面的运用。


我的github:https://github.com/raylee2015/DeepIntoThread



从头认识多线程-1.9 迫使线程停止的方法-return法

标签:into   ted   主线程   sys   这一   extends   java   github   array   

原文地址:http://www.cnblogs.com/yxysuanfa/p/7296037.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!