首页 > 代码库 > JAVA中创建线程的方法及比较

JAVA中创建线程的方法及比较

 

  JAVA中提供了Thread类来创建多线程的应用,常用的方式有以下2种。

 

一、实现Runnable接口来创建线程

1、创建一个任务类,实现Runnable接口,并重写run()方法,run()方法中的内容就是需要线程完成的任务。

2、创建一个任务类的对象。

3、任务类必须在线程中执行,因此将任务类的对象作为参数,创建一个Thread类对象,该Thread类对象才是真正的线程对象。

4、调用Thread线程类对象的start()方法,来启动一个线程。

代码实例:

 1 public class TestThread implements Runnable { 2     public void run() { 3         for (int i = 0; i < 20; i++) { 4             // 获取线程名称,默认格式:Thread-0 5             System.out.println(Thread.currentThread().getName() + " " + i); 6         } 7     } 8  9     public static void main(String[] args) {10         TestThread tt1 = new TestThread();11         TestThread tt2 = new TestThread();12         // 可为线程添加名称:Thread t1 = new Thread(tt1, "线程1");13         Thread t1 = new Thread(tt1);14         Thread t2 = new Thread(tt2);15         t1.start();16         t2.start();17     }18 }

 

二、继承Thread类来创建线程

1、创建一个任务类,继承Thread线程类,并重写run()方法,run()方法中的内容就是需要线程完成的任务。

2、创建一个任务类的对象,即创建了线程对象。

3、调用任务类对象的start()方法,来启动一个线程。

代码实例:

 1 public class TestThread extends Thread { 2     public void run() { 3         for (int i = 0; i < 20; i++) { 4             // 与Thread.currentThread().getName()相同 5             System.out.println(this.getName() + " " + i); 6         } 7     } 8  9     public static void main(String[] args) {10         TestThread t1 = new TestThread();11         TestThread t2 = new TestThread();12         t1.start();13         t2.start();14     }15 }

 

三、实现Runnable接口与继承Thread类来创建线程的比较

1、实现Runnable接口的方式:

(1)优点:编写稍微复杂,任务类中访问当前线程时,必须使用Thread.currentThread()方法。

(2)缺点:任务类只实现了Runnable接口,还可以继承其他类。这种方式,可以多个线程对象共享一个任务类对象,即多线程共享一份资源的情况,如下:

1     TestThread tt1 = new TestThread();2     Thread t1 = new Thread(tt1);3     Thread t2 = new Thread(tt1);4     t1.start();5     t2.start();

2、继承Thread类方式:

(1)优点:编写简单,任务类中访问当前线程时,可以直接使用this关键字。

(2)缺点:任务类即县城类已经继承了Thread类,所以不能再继承其他父类。

 

  总结:在仅仅只重写run()方法,而不重写Thread类其他方法的前提下,比较推荐实现Runnable接口的方式创建线程。

 

JAVA中创建线程的方法及比较