zoukankan      html  css  js  c++  java
  • Java 创建线程/停止线程

     继承 Thread 类

    class MyThread1 extends Thread{
        @Override
        public void run(){
            System.out.println("继承 Thread ...");
        }
    }
    
    public class Test1 extends Thread {
        public static void main(String[] args) {
            new MyThread1().start();
        }
    }

    实现 Runnable 接口

    class MyThread implements Runnable{
    
        @Override
        public void run() {
            System.out.println("继承 Runnable ......");
        }
    }
    public class Test1 {
        public static void main(String[] args) {
            // 创建真实对象
            MyThread myThread = new MyThread();
            // 创建代理对象
            Thread t = new Thread(myThread);
            t.start();
        }
    }

    实现 Callable 接口

    class MyThread implements Callable<String> {
    
        @Override
        public String call() throws Exception {
            return "hello world!";
        }
    }
    public class Test1 {
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            // 创建对象
            MyThread myThread = new MyThread();
            // 创建线程, 使用线程调度服务来创建, 参数表示创建线程的数量
            ExecutorService t = Executors.newFixedThreadPool(1);
            // 执行线程
            Future<String> result = t.submit(myThread);
            // 获取线程执行结果的返回值, 将会等待线程执行结束
            String s = result.get();
            System.out.println(s);
         // 停止线程
            t.shutdownNow();
        }
    }

    龟兔晒跑

    class MyThread implements Callable<String> {
         // 步数, 记录跑步的数量, 初始化为 0
        private int step = 0;
         // 停止线程的标识, 为 false 就跳出循环(线程体)
        private boolean flag = true;
         // 线程名称, 标识小兔子和乌龟
        private String name;
    
        public boolean getFlag(){
            return this.flag;
        }
    
        public void setFlag(boolean flag) {
            this.flag = flag;
        }
    
         // 频率, 多少毫秒跑一步, 小兔子和老乌龟是不一样的
        private long time;
    
        public MyThread(String name, long time) {
            this.name = name;
            this.time = time;
        }
    
        @Override
        public String call() throws Exception {
            // 获取 flag , 如果是 true 就执行循环体
            while (this.getFlag()) {
                step++;
                Thread.sleep(time);
            }
            return name + "跑了" + step + "步";
        }
    }
    
    public class Test1 {
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            MyThread rabbit = new MyThread("小兔子", 500);
            MyThread tortoise = new MyThread("老乌龟", 1000);
            // 创建线程, 通过线程调度服务来创建, 参数表示线程数量
            ExecutorService threadService = Executors.newFixedThreadPool(2);
            // 执行线程
            Future<String> rabbitResult = threadService.submit(rabbit);
            Future<String> tortoiseResult = threadService.submit(tortoise);
            // 2 秒后小兔子和乌龟停止跑步, Callable 可以抛异常
            Thread.sleep(2000);
            rabbit.setFlag(false);
            tortoise.setFlag(false);
            // 获取结果
            String s = rabbitResult.get();
            String s2 = tortoiseResult.get();
            // 打印结果
            System.out.println(s);
            System.out.println(s2);
            // 停止服务
            threadService.shutdownNow();
        }
    }

     停止线程

      停止线程的方法被废弃了, 如果需要停止需要手动实现, 步骤如下:

        1, 线程类中定义一个成员变量

        2, 线程体中使用该变量

        3, 对外提供方法改变标识

    class MyThread2 implements Runnable{
    
        // 定义一个变量, 用于控制停止线程
        private boolean flag = true;
    
        public boolean getFlag() {
            return flag;
        }
        // 对外提供修改值的方法
        public void setFlag(boolean flag) {
            this.flag = flag;
        }
    
        @Override
        public void run() {
            // 循环获取变量 flag 值, 如果是 true 就执行
            while (this.getFlag()){
                System.out.println("根本停不下来...");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public class Test2 {
    
        public static void main(String[] args) throws InterruptedException {
            MyThread2 myThread2 = new MyThread2();
            new Thread(myThread2).start();
    
            // 两秒后停止线程
            Thread.sleep(200);
            myThread2.setFlag(false);
        }
    
    }
  • 相关阅读:
    POJ 1611 The Suspects
    POJ 2001 Shortest Prefixes(字典树)
    HDU 1251 统计难题(字典树 裸题 链表做法)
    G++ C++之区别
    PAT 乙级 1013. 数素数 (20)
    PAT 乙级 1012. 数字分类 (20)
    PAT 乙级 1009. 说反话 (20)
    PAT 乙级 1008. 数组元素循环右移问题 (20)
    HDU 6063 17多校3 RXD and math(暴力打表题)
    HDU 6066 17多校3 RXD's date(超水题)
  • 原文地址:https://www.cnblogs.com/huanggy/p/9523111.html
Copyright © 2011-2022 走看看