java_线程创建的三种方式及区别
java中关于线程的创建有三种: (1)通过继承Thread类创建线程.
(2)通过实现Runnable接口创建线程.
(3)通过Callable 和 Future 接口创建线程.
* * * * * * * * * * * * * * * * * * * * * * * * * 继承Thread类创建线程 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
1)重写run()方法, 该方法的方法体是线程需要执行的任务;
2)启动线程, 调用start();
代码 :
1 package demo; 2 3 public class TestThread{ 4 5 public static void main(String[] args) { 6 Thread thread = new MyThread(); 7 thread.start(); 8 } 9 } 10 11 class MyThread extends Thread{ 12 13 public void run() { 14 try { 15 System.out.println("稍等下!"); 16 sleep(5000); 17 System.out.println(getName()+"执行了!"); 18 } catch (InterruptedException e) { 19 e.printStackTrace(); 20 } 21 } 22 }
* * * * * * * * * * * * * * * * * * * * * * * * * 实现Runnable接口创建线程 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
1. 覆盖接口中run()方法, 该方法的方法体是线程需要执行的任务;
2. 通过实现Thread类的构造函数Thread(Runnable target)或Thread(Runnable target, String name)来创建Thread实例, 这样就创建一个完整的线程对象;
3. 启动线程, 调用start();
代码 :
1 package demo; 2 3 public class TestRunnable{ 4 5 public static void main(String[] args) { 6 Thread thread=new Thread(new MyThread2()); 7 Thread thread1=new Thread(new MyThread2()); 8 thread.start(); 9 thread1.start(); 10 } 11 } 12 13 class MyThread2 implements Runnable{ 14 15 public void run() { 16 try { 17 System.out.println("稍等下!"); 18 Thread.sleep(500); 19 for(int i=0;i<100;i++){ 20 System.out.println(Thread.currentThread().getName()+"线程的"+i+"执行了!"); 21 } 22 } catch (InterruptedException e) { 23 e.printStackTrace(); 24 } 25 } 26 }
* * * * * * * * * * * * * * * * * * * * * * * 实现Callable接口与Future接口创建线程 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
继承类与实现接口的区别 ?
1. 将线程的任务从线程的子类中分离出来, 进行单独的封装, 按照面向对象的思想将任务封装为对象.
2. 避免java单继承的局限性.