JAVA-创建线程的方式

71 阅读1分钟

一、创建线程的方式有哪些?

1. 继承Thread类,重写run方法,调用start方法。

public class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println("执行业务逻辑");
    }
}

class Application {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
    }
}

2. 实现Runnable接口,实现run方法,将该实现传入Thread的构造函数中,调用start方法。

public class MyRunnable implements Runnable{

    @Override
    public void run() {
        System.out.println("执行业务逻辑");
    }
}
class Application1 {
    public static void main(String[] args) {
        new Thread(new MyRunnable()).start();
    }
}

3. 实现Callable接口,并结合FutureTask实现。

  1. 定义一个Callable实现类,并实现call方法。call方法是带返回值的。
  2. 然后通过FutureTask的构造方法,把Callable实现类传进去。
  3. 把FutureTask作为Thread类的target,创建Thread线程对象。
  4. 通过FutureTask的get方法获取线程的执行结果。
public class MyCallable implements Callable<String> {

    @Override
    public String call() throws Exception {
        System.out.println("执行业务逻辑");
        return "成功";
    }
}
class Application2 {
    public static void main(String[] args) {
        //Callable结合FutureTask使用
        FutureTask<String> futureTask = new FutureTask<>(new MyCallable());
        new Thread(futureTask).start();
        try {
            String threadResult = futureTask.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}

4. 使用JDK自带的Executors来创建线程池对象。

public class ThreadPool {

    public void pool() {
        //自定义线程池
        ExecutorService threadPool = new ThreadPoolExecutor(
                5,
                10,
                50,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue(100),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        threadPool.execute(new MyRunnable());

        //使用Executors工具创建线程池
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
        fixedThreadPool.submit(new MyCallable());
    }
}