加入收藏 | 设为首页 | 会员中心 | 我要投稿 云计算网_泰州站长网 (http://www.0523zz.com/)- 视觉智能、AI应用、CDN、行业物联网、智能数字人!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

Java多线程的达成方法

发布时间:2021-12-09 16:21:41 所属栏目:PHP教程 来源:互联网
导读:Java虚拟机允许应用程序并发地运行多个线程。在Java语言中,多线程的实现一般有以下三种方法: 1)实现Runnable接口,并实现该接口的run()方法 class MyThread implements Runnable { public void run(){ System.out.println(Thread Body); } } public class

Java虚拟机允许应用程序并发地运行多个线程。在Java语言中,多线程的实现一般有以下三种方法:
 
1)实现Runnable接口,并实现该接口的run()方法
 
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();
  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()方法
 
Callable对象实际是属于Executor框架中的功能类,Callable接口与Runnable接口类似,但是提供了比Runnable更强大的功能,主要表现在以下三点:
 
(1)Callable可以在任务结束后提供一个返回值,Runnable无法提供这个功能。
 
(2)Callable中的call()方法可以抛出异常,而Runnable的run()方法不能抛出异常。
 
(3)运行Callable可以拿到一个Future对象,Future对象表示异步计算的结果。它提供了检查计算是否完成的方法。由于线程属于异步计算模型,所以无法从其他线程中得到方法的返回值,在这种情况下,就可以使用Future来监视目标线程调用call()方法的情况,当调用Future的get()方法获取结果时,当前线程就会阻塞,直到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();
    }
 }
}

(编辑:云计算网_泰州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读