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

猜你喜欢

转载自www.linuxidc.com/Linux/2017-04/142468.htm