zoukankan      html  css  js  c++  java
  • 从头认识多线程-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



  • 相关阅读:
    【onenet-edp传输】1、调试上报数据点和端对端透传
    【PYQT5快速开发】重定义边框、QSS美化皮肤主题
    MySQL
    Flask-Login一个账号单用户在线
    DataTable按钮,排序,单元格颜色
    python
    MegaCli64 raid对应关系
    openstack server status
    js中使用JSON.parse转换json
    linux使用pyodbc和freetds连接sqlserver
  • 原文地址:https://www.cnblogs.com/yxysuanfa/p/7296037.html
Copyright © 2011-2022 走看看