欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

线程创建的四种方式

程序员文章站 2022-06-21 10:45:11
...

方式一: 继承Thread类

public class thread {

    public static void main(String[] args) {
        thread1 thread1=new thread1();
        Thread thread=new Thread(thread1);
        thread.start();
    }
}
class thread1 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i <3 ; i++) {
            System.out.println("thread1:"+currentThread().getName());
        }
    }
}

线程创建的四种方式

方式二: 实现Runnable接口

public class thread {

    public static void main(String[] args) {
        thread2 thread2=new thread2();
        Thread thread=new Thread(thread2);
        thread.start();

    }
}
class thread2 implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i <3 ; i++) {
            System.out.println("thread2:"+Thread.currentThread().getName());
        }
    }
}

线程创建的四种方式

方式三: 实现Callable接口

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class thread {

    public static void main(String[] args) throws Exception {
        thread3 thread3=new thread3();
        FutureTask futureTask=new FutureTask(thread3);
        Thread thread=new Thread(futureTask);
        thread.start();
    }
}
class thread3 implements Callable{

    @Override
    public Object call() throws Exception {
        for (int i = 0; i <3 ; i++) {
            System.out.println("thread3:"+Thread.currentThread().getName());
        }
        return true;
    }
}

线程创建的四种方式

方式四: 线程池

import java.util.concurrent.*;
public class thread {

    public static void main(String[] args) throws Exception {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 2L, TimeUnit.SECONDS, new LinkedBlockingDeque<>(1), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        try {
            for (int i = 0; i < 3; i++) {
                threadPoolExecutor.execute(() -> {
                    System.out.println("thread4:" + Thread.currentThread().getName());
                });
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPoolExecutor.shutdown();

        }
    }
}

线程创建的四种方式
线程池的具体原理可以看我的线程池那片文章。