从头认识多线程-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



你可能感兴趣的:(多线程)