码迷,mamicode.com
首页 > 编程语言 > 详细

Java多线程(一)

时间:2017-04-02 18:28:40      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:ice   stc   ring   callable   imp   cat   java多线程   stack   let   

线程问题,或称并发

创建线程一般有一下方法

  • 继承Thread类,重写run方法
    1 public class TestThread extends Thread{ 
    2     public void run() {
    3             System.out.println("Hello World");
    4         }  
    5     public static void main(String[] args) {
    6         Thread mThread = new TestThread();
    7         mThread.start(); 
    8     } 
    9 }

     

  • 实现Runnable接口,并实现run方法
     1 public class TestRunnable implements Runnable {
     2     public void run() { 
     3             System.out.println("Hello World");
     4         } 
     5 }
     6 
     7 public class TestRunnable {
     8     public static void main(String[] args) {
     9         TestRunnable mTestRunnable = new TestRunnable();      
    10         Thread mThread = new Thread(mTestRunnable);
    11         mThread.start(); 
    12     } 
    13 }

    注意:Runnable 不是线程而是进程,或者称为thread的一个target

    • 实现Callable接口,重写call()方法
      public class TestCallable {  
          public static class MyTestCallable  implements Callable {  
              public String call() throws Exception {  
                   retun "Hello World";
                  }  
              }  
      public static void main(String[] args) {  
              MyTestCallable mMyTestCallable= new MyTestCallable();  
              ExecutorService mExecutorService = Executors.newSingleThreadPool();  
              Future mfuture = mExecutorService.submit(mMyTestCallable);  
              try { 
                  System.out.println(mfuture.get());  
              } catch (Exception e) {  
                 e.printStackTrace();
              } 
          }  
      }

      此处runnable和Callable接口的区别主要体现在后者可以得到一个返回值  并可以抛出异常,而前者不可以。本示例是在一个线程池当中实现的该接口。利用

      newSingleThreadPool方法去创建一个线程池

Java多线程(一)

标签:ice   stc   ring   callable   imp   cat   java多线程   stack   let   

原文地址:http://www.cnblogs.com/zhangqiuchi/p/6659436.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!