anxiao

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";
    }
}

 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-11-17
  • 2021-11-17
  • 2021-08-25
  • 2021-07-20
  • 2021-11-17
  • 2021-11-17
  • 2021-08-19
猜你喜欢
  • 2021-12-22
  • 2021-10-20
  • 2021-11-17
  • 2021-12-03
  • 2021-11-17
相关资源
相似解决方案