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!");
    }
}

 

posted on 2021-01-20 13:23  懂技术爱生活  阅读(63)  评论(0编辑  收藏  举报

导航