• 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!");
        }
    }
  • 相关阅读:
    TheFourthJavaText
    Java语法基础总结
    课程作业02
    读大道至简第二章感悟
    课时作业
    读大道至简——编程的精义感想
    使用Mybatis
    使用matlab遇到的问题
    machine learning (7)---normal equation相对于gradient descent而言求解linear regression问题的另一种方式
    machine learning (6)---how to choose features, polynomial regression
  • 原文地址:https://www.cnblogs.com/javapath/p/14302350.html
Copyright © 2020-2023  润新知