zoukankan      html  css  js  c++  java
  • 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();
         }
     }
    }
  • 相关阅读:
    Python 设置 IP 代理 访问网页 ( 用户名密码验证代理 )
    Squid 3.3 部署 HTTP代理服务器
    文件打开模式 w+ r+ a+ 区别和辨析
    Python 学习工具书
    Conference Related to social network.
    Linux 使用故障小记
    正则表达式学习连接
    再次被windows操作系统伤害之吐槽
    数据结构——线性表的顺序表示(1)
    斐波那契数列两种算法的时间复杂度
  • 原文地址:https://www.cnblogs.com/ChanSS/p/6661432.html
Copyright © 2011-2022 走看看