创建线程的几种方式

  • 继承Thread类创建线程
  • 实现Runnable接口创建线程
  • 使用Callable和Future创建线程
  • 使用线程池例如用Executor框架





SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

1、继承Thread类重写run方法创建线程

public class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println("thread name is:" + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
    }
}
thread name is:Thread-0





2、实现Runnable接口重写run方法创建线程

public class MyRunnable implements Runnable {

    @Override
    public void run() {
        System.out.println("thread name is:" + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread t = new Thread(myRunnable);
        t.start();
    }
}
thread name is:Thread-0





3、使用Callable和Future创建线程

public class MyCallable implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        System.out.println("thread name is:" + Thread.currentThread().getName());
        return 1;
    }

    public static void main(String[] args) {
        MyCallable myCallable = new MyCallable();
        FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
        Thread t = new Thread(futureTask);
        t.start();
    }
}
thread name is:Thread-0





4、使用线程池创建线程

public class MyRunnable implements Runnable {

    @Override
    public void run() {
        System.out.println("thread name is:" + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        MyRunnable myRunnable = new MyRunnable();
        threadPool.execute(myRunnable);
        threadPool.shutdown();
    }
}
thread name is:pool-1-thread-1
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄