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

Posted yxysuanfa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从头认识多线程-1.9 迫使线程停止的方法-return法相关的知识,希望对你有一定的参考价值。

这一章节我们来讨论一下还有一种停止线程的方法-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法的主要内容,如果未能解决你的问题,请参考以下文章

从头认识多线程-4.3 ThreadLocal使用时需要注意的地方

JAVA-初步认识-第十四章-多线程-停止线程方式-定义标记

JAVA-初步认识-第十四章-多线程-停止线程方式-interrupt

从头认识多线程-2.24 修改监视器对同步的影响

从头认识多线程-1.16 对照不同的优先级

从头认识多线程-3.1 使用volatile解决异步死循环