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