zoukankan      html  css  js  c++  java
  • 多线程之创建线程有哪几种方式?

    这个问题一般会出现在面试当中,多线程创建有哪几种方式呢?
    答:实现Runable接口和实现Thread类。

    我们先看看看实现这两种的实现方式

     1 package com.summer;
     2 
     3 public class ThreadA implements Runnable {
     4 
     5     public void run() {
     6         System.out.println("start ThreadA!");
     7     }
     8 
     9     public static void main(String[] args) {
    10         Thread thread = new Thread(new ThreadA());
    11         thread.start();
    12     }
    13 }
     1 package com.summer;
     2 
     3 public class ThreadB extends Thread {
     4 
     5     @Override
     6     public void run() {
     7         System.out.println("start ThreadB!");
     8     }
     9 
    10     public static void main(String[] args) {
    11         ThreadB threadB = new ThreadB();
    12         threadB.start();
    13     }
    14 }

    那么除了这两种方式以外还有什么其他方式呢?

    答:可以实现Callable接口和线程池来创建线程。

     1 package com.summer;
     2 
     3 import java.util.concurrent.Callable;
     4 import java.util.concurrent.FutureTask;
     5 
     6 public class ThreadC implements Callable {
     7 
     8     public Object call() throws Exception {
     9         System.out.println("start ThreadC!");
    10         return null;
    11     }
    12 
    13     public static void main(String[] args) {
    14         ThreadC threadC = new ThreadC();
    15         FutureTask futureTask = new FutureTask(threadC);
    16         Thread thread = new Thread(futureTask);
    17         thread.start();
    18     }
    19 }
     1 package com.summer;
     2 
     3 import java.util.concurrent.ExecutorService;
     4 import java.util.concurrent.Executors;
     5 
     6 public class ThreadD implements Runnable {
     7 
     8     public void run() {
     9         System.out.println("start ThreadD!");
    10     }
    11 
    12     public static void main(String[] args) {
    13         ExecutorService executorService = Executors.newSingleThreadExecutor();
    14         executorService.execute(new ThreadD());
    15     }
    16 }
  • 相关阅读:
    npm使用淘宝镜像源
    MapReduce任务执行源码分析
    spark.sql.shuffle.partitions到底影响什么
    hdfs的写入数据流程及异常情况分析
    面试题
    HDFS的双缓冲机制详解
    rpm包无法卸载
    hive建表支持的文件类型与压缩格式
    centos6中同时安装python3.7与python2.6
    linux centos6.x安装mysql5.6.33版本
  • 原文地址:https://www.cnblogs.com/tanyang/p/11176103.html
Copyright © 2011-2022 走看看