Java多线程中创建线程的方法有哪些

发布时间:2021-06-07 13:07:22 作者:小新
来源:亿速云 阅读:161

这篇文章主要介绍Java多线程中创建线程的方法有哪些,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

1.实现Runnable接口,重载run(),无返回值

package thread;
 
public class ThreadRunnable implements Runnable {
  public void run() {
    for (int i = 0; i < 10; i++) {
      System.out.println(Thread.currentThread().getName() + ":" + i);
    }
  }
}
 
 
package thread;
 
public class ThreadMain {
  public static void main(String[] args) throws Exception {
    ThreadRunnable threadRunnable1 = new ThreadRunnable();
    ThreadRunnable threadRunnable2 = new ThreadRunnable();
    ThreadRunnable threadRunnable3 = new ThreadRunnable();
    ThreadRunnable threadRunnable4 = new ThreadRunnable();
    Thread thread1 = new Thread(threadRunnable1);
    Thread thread2 = new Thread(threadRunnable2);
    Thread thread3 = new Thread(threadRunnable3);
    Thread thread4 = new Thread(threadRunnable4);
    thread1.start();
    thread2.start();
    thread3.start();
    thread4.start();
  }
}

2.继承Thread类,复写run()

使用时通过调用Thread的start()(该方法是native),再调用创建线程的run(),不同线程的run方法里面的代码交替执行。

不足:由于java为单继承,若使用线程类已经有个父类,则不能使用该方式创建线程。

public class ThreadEx extends Thread {
  public void run() {
    for (int i = 0; i < 10; i++) {
      System.out.println(Thread.currentThread() + ":" + i);
    }
  }
}
 
 
public class ThreadMain {
  public static void main(String[] args)
  {
    ThreadEx threadEx = new ThreadEx();
    threadEx.start();
  }
}

3.实现Callable接口,通过FutureTask/Future来创建有返回值的Thread线程,通过Executor执行

补充:与实现Runnable接口类似,都是实现接口,不同的是该方式有返回值,可以获得异步执行的结果。

延伸:FutureTask是类,Future是接口。

package thread;
 
import java.util.concurrent.*;
 
public class ThreadCallable {
  public static void main(String[] args) throws Exception {
    FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
      public Integer call() throws Exception {
        for (int i = 0; i < 10; i++) {
          System.out.println(Thread.currentThread().getName() + ":" + i);
        }
        return 1;
      }
    });
    Executor executor = Executors.newFixedThreadPool(1);
    ((ExecutorService) executor).submit(futureTask);
 
    //获得线程执行状态
    System.out.println(Thread.currentThread().getName() + ":" + futureTask.get());
  }
}

4.使用Executors创建ExecutorService,入参Callable或Future

补充:适用于线程池和并发

package thread;
 
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
 
import static java.lang.Thread.sleep;
 
public class ThreadExecutors {
  private final String threadName;
 
  public ThreadExecutors(String threadName) {
    this.threadName = threadName;
  }
 
  private ThreadFactory createThread() {
    ThreadFactory tf = new ThreadFactory() {
      public Thread newThread(Runnable r) {
        Thread thread = new Thread();
        thread.setName(threadName);
        thread.setDaemon(true);
        try {
          sleep(1000);
        }
        catch (InterruptedException e) {
          e.printStackTrace();
        }
        return thread;
      }
    };
    return tf;
  }
 
  public Object runCallable(Callable callable) {
    return Executors.newSingleThreadExecutor(createThread()).submit(callable);
  }
 
  public Object runFunture(Runnable runnable) {
    return Executors.newSingleThreadExecutor(createThread()).submit(runnable);
  }
}
 
 
 
package thread;
 
import java.util.concurrent.*;
 
public class ThreadMain {
  public static void main(String[] args) throws Exception {
    ThreadExecutors threadExecutors = new ThreadExecutors("callableThread");
    threadExecutors.runCallable(new Callable() {
      public String call() throws Exception {
        return "success";
      }
    });
 
    threadExecutors.runFunture(new Runnable() {
      public void run() {
        System.out.println("execute runnable thread.");
      }
    });
  }
}

5 Runnable接口和Callable接口区别

  1. 1)两个接口需要实现的方法名不一样,Runnable需要实现的方法为run(),Callable需要实现的方法为call()。

  2. 2)实现的方法返回值不一样,Runnable任务执行后无返回值,Callable任务执行后可以得到异步计算的结果。

  3. 3)抛出异常不一样,Runnable不可以抛出异常,Callable可以抛出异常。

6 Callable返回值意义在哪儿,不要返回值可以吗,什么时候需要用到返回值?

首先Callable是线程异步执行的结果状态,如果有两个线程A和B,B中的某个业务逻辑中需要确定A结束后才能进行,那么就需要获得线程A的执行结果。

设计背景:一个任务需要进行一系列操作,比如拷贝大量的基础数据,以及解析数据,并入库,由于数量大,整个过程需要持续十秒左右,用户体验差,需要降低到2~5s。

设计思路:经过分解过程,将拷贝数据分为一个过程,同时涵盖部分解析数据功能,剩下解析数据划为一个过程,两个过程异步执行,其中最后一个任务状态入库时需要将所有业务操作都执行完成后更新,此时就需要用到线程中的返回值。

以上是“Java多线程中创建线程的方法有哪些”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. java创建线程的方法
  2. Java有几种创建线程池的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java 多线程

上一篇:vue-cli如何创建的项目配置多页面

下一篇:如何创建自定义的Angular Schematics

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》