美文网首页
创建线程的方式

创建线程的方式

作者: LiuXiaozhang | 来源:发表于2019-07-30 15:27 被阅读0次

1创建线程的几种方式
a.继承Thread类实现多线程
b.实现Runnable接口方式实现多线程
c.使用ExecutorService、Callable、Future实现有返回结果的多线程(线程池)

A

  //• 定义一个继承Thread类的子类,并重写该类的run()方法;
  // • 创建Thread子类的实例,即创建了线程对象;
 //   • 调用该线程对象的start()方法启动线程。

class SomeThead extends Thraad   { 
    public void run()   { 
     //do something here  
    }  
 } 
 
public static void main(String[] args){
 SomeThread oneThread = new SomeThread();   
  步骤3:启动线程:   
 oneThread.start(); 
}

B

// 定义Runnable接口的实现类,并重写该接口的run()方法;
//创建Runnable实现类的实例,并以此实例作为Thread的target对象,即该Thread对象才是真正的线程对象。


class SomeRunnable implements Runnable   { 
  public void run()   { 
  //do something here  
  }  
} 
Runnable oneRunnable = new SomeRunnable();   
Thread oneThread = new Thread(oneRunnable);   
oneThread.start(); 

C

//实现Callable接口  泛型和返回值的类型相同

public class MyCallable implements Callable<String>{
    public String call() throws Exception {
        return "abc";
    }


public class Demo01 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        //1.从线程池工厂中获取线程池对象
        ExecutorService es=Executors.newFixedThreadPool(2);
        //2.创建线程任务对象
        MyCallable mc=new MyCallable();
        //3.让线程池自主选择一条线程执行线程任务
        Future<String>    f=es.submit(mc);
        //4.获取线程任务的返回值
        System.out.println(f.get());
    }
}

Runnable和Callable的区别

1.Runnable执行方法是run(),Callable是call()

  1. 实现Runnable接口的任务线程无返回值;实现Callable接口的任务线程能返回执 行结果
  2. call方法可以抛出异常,run方法若有异常只能在内部消化

相关文章

  • iOS基础知识 (三)

    多线程 多线程创建方式 iOS创建多线程方式主要有NSThread、NSOperation、GCD,这三种方式创建...

  • iOS 多线程-NSThread

    1. 创建和启动线程 创建、启动线程 2. 其他创建线程方式 创建线程后自动启动线程[NSThread detac...

  • iOS 多线程开发

    一、NSThread 1、创建和启动线程 2、其他创建线程方式 上述2种创建线程方式的优缺点优点:简单快捷缺点:无...

  • 多线程编程

    创建线程 创建线程的三种方式 创建方式Threadclass继承Thread类(重点)Runnable接口实现Ru...

  • 2018-10-26怎么创多线程

    创建线程方式1:直接通过Thread类创建对象,将需要在子线程中执行的函数作为target参数传进去 创建线程方式...

  • java中创建线程池的方式

    创建线程池的方式: 使用Java提供的用于管理线程池的接口ExecutorService 创建线程池,共有四种方式...

  • iOS 线程

    pthread NSThread 第一种创建方式 第二种创建方式 第三种创建线程的方式 NSThread线程的状态...

  • 其他快速开启线程的方法

    创建线程后自动启动线程 隐式创建并启动线程 ● 上述2种创建线程方式的优缺点● 优点:简单快捷● 缺点:无法对线程...

  • 线程

    java 中创建线程有哪几种方式? Java中创建线程主要有三种方式: 一、继承Thread类创建线程类 (1)定...

  • 线程创建方式

    方法一:继承Thread类,作为线程对象存在(继承Thread对象)让线程等待的方法Thread.sleep(20...

网友评论

      本文标题:创建线程的方式

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