Java 多線程實戰


Java多線程

public class ThreadTest {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 啟動一個線程
        new Thread(new MyRunnable()).start();
        new MyThread().start();
        
        FutureTask<String> task = new FutureTask<String>(new MyCallable());
        new Thread(task).start();
        System.out.println("The result of task is " + task.get());
        
        // 使用線程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        executorService.execute(new MyRunnable());
        executorService.execute(new MyThread());
        executorService.submit(task);
        System.out.println("The result of task is " + task.get());
        executorService.shutdown();
    }
}

class MyRunnable implements Runnable {    
    @Override
    public void run() {
        System.out.println("This is MyRunnable...");
    }
}

class MyThread extends Thread { 
    @Override
    public void run() {
        System.out.println("This is MyThread...");
    }
}

class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        System.out.println("This is MyCallable...");
        return "SUCCESS";
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM