創建線程的幾種方式

繼承Thread類

public class ExtendsThreadTest extends Thread {
    @Override
    public void run() {
        System.out.println("thread is running!");
    }
    public static void main(String[] args) {
        ExtendsThreadTest et1 = new ExtendsThreadTest();
        et1.start();
    }
}

實現Runnable接口

public class RunnableTest implements Runnable{
    @Override
    public void run() {
        System.out.println("thread is running!");
    }
    public static void main(String[] args) {
        Thread t1 = new Thread(new RunnableTest());
        t1.start();
    }
}

匿名內部類的兩種寫法

public class App {
    public static void main(String[] args){
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread1 is running!");
            }
        }){}.start();

        new Thread(){
            @Override
            public void run(){
                System.out.println("thread2 is running!");
            }
        }.start();
    }
}

基於java.util.concurrent.Callable工具類的實現,帶返回值

public class CallableTest {
    public static void main(String[] args) throws Exception {
        Callable<Integer> call = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println("thread is running!");
                return 1;
            }
        };
        FutureTask<Integer> task = new FutureTask<>(call);
        Thread t =  new Thread(task);
        t.start();
    }
}

基於java.util.Timer工具類的實現

public class TimerTest {
    public static void main(String[] args) throws Exception {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("thread is running!");
            }
        }, new Date());
    }
}

基於java.util.concurrent.Executors工具類,基於線程池的實現

public class ThreadPoolTest {
    public static void main(String[] args) {
        // 創建線程池
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        while(true) {
            threadPool.execute(new Runnable() { // 提交多個線程任務,並執行
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + " is running ..");
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
更多信息可以關注我的個人博客:逸竹小站逸竹小站

也歡迎關注我的公衆號:yizhuxiaozhan,二維碼:公衆號二維碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章