美文网首页
java中实现多线程的方式

java中实现多线程的方式

作者: 小院看客 | 来源:发表于2023-06-03 21:13 被阅读0次

    1、继承Thread类实现

    public class MyThread extends Thread{
      public static void main(String[] args){
        MyThread thread = new MyThread();
        thread.start();
      }
    
      @override
      public void run(){
        System.out.println("hello");
      }
    }
    

    重写的是run方法
    2、实现Runnable接口

    public class MyThread implements Runnable{
      public static void main(String[] args){
        Thread thread = new Thread(new MyThread());
        thread.start();
      }
      public void run(){
        System.out.println("hello");
      }
    }
    

    3、实现Callable接口

    public class MyThread implements Callable<String>{
      public static void main(String[] args) throws ExecutionException, InterruptedException {
            FutureTask<String> futureTask = new FutureTask<>(new MyThread());
            Thread thread = new Thread(futureTask);
            thread.start();
            String result = futureTask.get();
            System.out.println(result);
        }
    
        @Override
        public String call() throws Exception {
            return "hello";
        }
    }
    

    实现call方法,得使用Thread+FutureTask,这种方式支持拿到异步执行任务的结果。
    4、线程池方式

    相关文章

      网友评论

          本文标题:java中实现多线程的方式

          本文链接:https://www.haomeiwen.com/subject/kcvvedtx.html