实现线程的三种方式

    在java语言中,多线程的实现一般有以下三种方式:

        1)实现runnable接口,并实现该接口的run()方法。

        以下是主要步骤:

        ①自定义类并实现Ruannable接口,实现run()方法。

        ②创建Thread对象,用实现Ruannable接口的独享作为参数实例化该Thread对象。

        ③调用Thread的start()方法;

class MyThread implements Runnable
{
   //创建线程类
   public void run(){
      System.out.println("Thread Body");
   }
}

public class Test
{
  public static void main(String[] args){
   MyThread thread = New MyThread();
   Thread t = new Thread(thread);
   t.start();//启动线程
}
}

    2)继承Thread类,重写run方法。

    

class MyThread extends Thread{
  public void run(){
     System.out.println("Thread Body");
  }
}
public class Test{
  public static void main(String[] args){
  MyThread thread = New MyThread();
  thread.start();
}
}

    3)实现Callable接口,重写call方法。

    

import java.util.concurrent.*;
 public class CallableAndFuture {  // 创建线程类 
 public static class CallableTest implements Callable<String>  {  
 public String call() throws Exception    {    return "Hello World!"; 
  } 
 }  
public static void main(String[] args)   {  
 ExecutorService threadPool = Executors.newSingleThreadExecutor();   // 启动线程   
Future<String> future = threadPool.submit(new CallableTest());
   try   {   
 System.out.println("waiting thread to finish");   
 System.out.println(future.get()); // 等待线程结束,并获取返回结果  
}   catch (Exception e)    {  
  e.printStackTrace(); 
  }  
} 
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值