1、继承Thread

  • 自定义类继承Thread,重写run()方法
  • main方法中start

    1. public class Main {
    2. public static void main(String[] args) {
    3. MyThread t1 = new MyThread();
    4. t1.start();
    5. MyThread t2 = new MyThread();
    6. t2.start();
    7. }
    8. static class MyThread extends Thread{
    9. @Override
    10. public void run() {
    11. super.run();
    12. System.out.println(Thread.currentThread().getName()+": start");
    13. try {
    14. Thread.sleep(3000);
    15. } catch (InterruptedException e) {
    16. e.printStackTrace();
    17. }
    18. System.out.println(Thread.currentThread().getName()+": end");
    19. }
    20. }
    21. }
  • 匿名内部类

    1. new Thread(){
    2. @Override
    3. public void run() {
    4. System.out.println(Thread.currentThread().getName()+": start");
    5. try {
    6. Thread.sleep(3000);
    7. } catch (InterruptedException e) {
    8. e.printStackTrace();
    9. }
    10. System.out.println(Thread.currentThread().getName()+": end");
    11. }
    12. }.start();

    2、实现Runnable

  • 自定义类实现Runnable接口,重写run()方法

  • 主线程中实例化该类,再把实例传给一个Thread

    1. public class Main {
    2. public static void main(String[] args) {
    3. MyRunnable r1 = new MyRunnable();
    4. Thread t1 = new Thread(r1);
    5. t1.start();
    6. MyRunnable r2 = new MyRunnable();
    7. Thread t2 = new Thread(r2);
    8. t2.start();
    9. }
    10. static class MyRunnable implements Runnable {
    11. @Override
    12. public void run() {
    13. System.out.println(Thread.currentThread().getName()+": start");
    14. try {
    15. Thread.sleep(3000);
    16. } catch (InterruptedException e) {
    17. e.printStackTrace();
    18. }
    19. System.out.println(Thread.currentThread().getName()+": end");
    20. }
    21. }
    22. }
  • 匿名内部类

    1. public class Main {
    2. public static void main(String[] args) {
    3. Thread t1 = new Thread(new Runnable() {
    4. @Override
    5. public void run() {
    6. System.out.println(Thread.currentThread().getName()+": start");
    7. try {
    8. Thread.sleep(3000);
    9. } catch (InterruptedException e) {
    10. e.printStackTrace();
    11. }
    12. System.out.println(Thread.currentThread().getName()+": end");
    13. }
    14. });
    15. t1.start();
    16. Thread t2 = new Thread(new Runnable() {
    17. @Override
    18. public void run() {
    19. System.out.println(Thread.currentThread().getName()+": start");
    20. try {
    21. Thread.sleep(3000);
    22. } catch (InterruptedException e) {
    23. e.printStackTrace();
    24. }
    25. System.out.println(Thread.currentThread().getName()+": end");
    26. }
    27. });
    28. t2.start();
    29. }
    30. }

    3、两种方法的区别

  • 继承Thread

    • 一个类只要继承了Thread类同时覆写了本类中的run()方法就可以实现多线程操作了
    • 但是一个类只能继承一个父类,这是此方法的局限
  • 实现Runnable
    • 程序开发中以实现Runnable接口为主
    • 避免单继承的局限,一个类可以实现多个接口
    • 适合于资源的共享
  • start和直接run的区别
    • start方法开始线程,处于就绪状态,等待CPU分配时间碎片
    • 直接调用run方法就是一个普通方法的调用