• 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();
         }
     }
    }
  • 相关阅读:
    oracle数据库导入导出命令!
    windows 7资源管理器崩溃解决方法
    迅雷和vs 2010的冲突
    当前网页正在试图打开您的受信任的站点列表中的站点,招人烦的alimama和淘宝
    <xhtmlConformance mode="Legacy"/>时,UpdatePanel会失效。
    头回遇见网上找不到的问题,“缺少实例ID,实例ID是必需的”
    修改基础表后,刷新关联视图的两种方法
    关于PetShop的一些记录。
    Linux poll机制分析
    volatile原理与技巧
  • 原文地址:https://www.cnblogs.com/ChanSS/p/6661432.html
Copyright © 2020-2023  润新知