好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java 并发编程中如何创建线程

简介

线程是基本的调度单位,它被包含在进程之中,是进程中的实际运作单位,它本身是不会独立存在。一个进程至少有一个线程,进程中的多个线程共享进程的资源。

Java中创建线程的方式有多种如继承Thread类、实现Runnable接口、实现Callable接口以及使用线程池的方式,线程池将在后面文章中单独介绍,这里先介绍另外三种方式。

继承Thread类

优点:在run方法里可以用this获取到当前线程。

缺点:由于Java不支持多继承,所以如果继承了Thread类后就不能再继承其他类。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

public class MyThread extends Thread {

  /**

   * 线程要执行的任务

   */

  @Override

  public void run() {

   System.out.println( "do something..." );

  }

 

  public static void main(String[] args) {  

     //创建线程

   MyThread myThread = new MyThread();

     //启动线程

   myThread.start();

  }

}

实现Runnable接口

优点:实现Runnable接口后不影响继承其他类,以及有利于多个线程资源共享。

缺点:获取当前线程需要调用Thread.currentThread()。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

public class MyThread implements Runnable {

   /**

   * 线程要执行的任务

   */

  @Override

  public void run() {

   System.out.println( "do something..." );

  }

 

  public static void main(String[] args) {

     //创建两个线程,并指定相同的任务

     Thread thread1 = new Thread( new MyThread());

   Thread thread2 = new Thread( new MyThread());

     //启动线程

   thread1.start();

   thread2.start();

  }

}

实现Callable接口

优缺点类似于实现Runnable接口,但是实现Callable接口可以有返回值。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

public class MyThread implements Callable<String> {

  /**

   * 线程要执行的任务,并且具有返回值

   */

  @Override

  public String call() throws Exception {

   System.out.println( "do something..." );

   Thread.sleep( 3000 );

   return "我是返回值" ;

  }

 

  public static void main(String[] args) throws ExecutionException, InterruptedException {

     //创建异步任务

   FutureTask<String> futureTask = new FutureTask( new MyThread());

     //启动线程

   new Thread(futureTask).start();

     //阻塞等待线程执行完成并返回结果

   String result = futureTask.get();

   System.out.println(result);

  }

}

以上就是Java 并发编程中如何创建线程的详细内容,更多关于Java 创建线程的资料请关注其它相关文章!

原文链接:https://www.cnblogs.com/seve/p/14483087.html

查看更多关于Java 并发编程中如何创建线程的详细内容...

  阅读:11次