建立線程的幾種方式

繼承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

基於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();
                    }
                }
            });
        }
    }
}複製代碼

更多信息能夠關注個人我的博客:逸竹小站逸竹小站ide

也歡迎關注個人公衆號:yizhuxiaozhan,二維碼:公衆號二維碼工具

相關文章
相關標籤/搜索