设为首页 加入收藏

TOP

Java多线程的实现方法
2017-04-07 10:25:33 】 浏览:6619
Tags:Java 线程 实现 方法

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();
    }
 }
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Java设计模式GOF之单例模式 下一篇Java虚拟机工作原理

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目