java之多线程的创建

多线程

进程、线程
进程:进程指正在运行的程序。一个程序进入内存运行即编程一个进程。
线程:进程中的执行单元,一个进程至少有一个线程,一个进程可以有多个线程。
多线程就是一个程序中有多个线程在同时执行。

创建线程的方式

1 继承Thread类

class MyThread extends Thread{
    @Override
    public void run(){
        System.out.println("MyThread1");
    }
}

2 实现Runnable接口

class MyRunnable implements Runnable{
    @Override
    public void run(){
        System.out.println("MyRunnable");
    }
}

3 使用Callable

class MyCallable implements Callable<Integer>{
    @Override
    public Integer call() throws Exception{
        System.out.println("MyCallable");
        return 1;
    }
}

4 Executor线程池框架

5 调用线程

//main方法调用线程
public class TestThread{
	public static void main(String[] args){
        //Thread
        new MyThread().start();

		//Runnable
        new Thread(new MyRunnable()).start();

		//Callable
        FutureTask<Integer> futureTask = new FutureTask<>(new MyCallable());
        new Thread(futureTask).start();
        try {
            Integer integer = futureTask.get();
            System.out.println("MyCallable返回值<FutureTask>:" + integer);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

		//线程池方式
		ExecutorService executorService = Executors.newFixedThreadPool(2);
        Future<Integer> result = executorService.submit(new MyCallable());
        try {
            Integer integer = result.get();
            System.out.println("MyCallable返回值<ExecutorService>:" + integer);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
	}
}

创建线程方式对比

继承Thread类缺点 : OOP的单继承局限性

Runable 和 Callable的区别
Callable 可获取执行结果,可抛出异常。Callable 如果需要访问当前线程,必须调用Thread.currentThread()方法

posted @ 2021-04-25 15:55  hinobody  阅读(51)  评论(0)    收藏  举报