zoukankan      html  css  js  c++  java
  • Java 四种创建线程方式

    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.*;
    
    public class ThreadTester {
    
        public static void main(String[] args) {
    
            // 1-继承Thread类
            MyThread thread1 = new MyThread();
            MyThread thread2 = new MyThread();
            thread1.start();
            thread2.start();
    
            // 2-实现Runnable接口
            MyRunableImpl runable = new MyRunableImpl();
            new Thread(runable).start();
            new Thread(runable).start();
    
            // 3-实现Callable接口
            FutureTask<String> futureTask = new FutureTask<>(new MyCallableImpl());
            new Thread(futureTask).start();
    
            try {
                String result = futureTask.get();
                System.out.println(result);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            // 4-使用ExecutorService实现
            ExecutorService poll = Executors.newFixedThreadPool(5);
            List<Future<String>> resuls = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                MyCallableImpl callable = new MyCallableImpl();
                Future<String> future = poll.submit(callable);
                resuls.add(future);
            }
            poll.shutdown();
            resuls.forEach((result) -> {
                String str = null;
                try {
                    str = result.get();
                    System.out.println(str);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            });
        }
    }
    
    class MyCallableImpl implements Callable<String> {
        @Override
        public String call() throws Exception {
            return Thread.currentThread().getName() + " run!";
        }
    }
    
    class MyRunableImpl implements Runnable {
        private int num = 10;
    
        @Override
        public synchronized void run() {
            for (int i = 0; i < 10 && this.num >= 0; i++) {
                System.out.println(Thread.currentThread().getName() + " num:" + this.num--);
            }
        }
    }
    
    class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println(this.getName() + " run!");
        }
    }
  • 相关阅读:
    制作windows服务
    DTCMS部署错误
    mysql常用操作
    eclipse maven jdk全局设置
    linux下安装lnmp环境
    aliyun阿里云Maven仓库地址——加速你的maven构建
    移动端前端框架UI库(Frozen UI、WeUI、SUI Mobile)
    getFields和getDeclaredFields
    2016暑假集训第三次训练赛题解
    HDU5863 cjj's string game(DP + 矩阵快速幂)
  • 原文地址:https://www.cnblogs.com/javapath/p/14302350.html
Copyright © 2011-2022 走看看