通过继承Thread类来实现多线程

继承Thread类需要重写run()方法,因为并不是所有的代码都要被线程执行,所以用run()方法来封装被线程执行的代码,直接调用run()方法时,相当于普通方法的调用,不会运行多线程,启动多线程需要用start()方法,然后由JVM调用此线程的run()方法。

  1. //创建三个线程分别输出"+"、"-"、"*"
  2. public class MyThread1 extends Thread {
  3. @Override
  4. public void run() {
  5. for (int i = 0; i < 2000; i++) {
  6. System.out.println("+");
  7. }
  8. }
  9. }
  10. public class MyThread2 extends Thread{
  11. @Override
  12. public void run() {
  13. for (int i = 0; i < 2000; i++) {
  14. System.out.println("-");
  15. }
  16. }
  17. }
  18. public class MyThread3 extends Thread{
  19. @Override
  20. public void run() {
  21. for (int i = 0; i < 2000; i++) {
  22. System.out.println("*");
  23. }
  24. }
  25. }
  26. //分别创建三个线程实例
  27. public class TestThread {
  28. public static void main(String[] args) {
  29. MyThread1 mt1=new MyThread1();
  30. MyThread2 mt2=new MyThread2();
  31. MyThread3 mt3=new MyThread3();
  32. // mt1.run();
  33. // mt2.run();
  34. // mt3.run();//分别输出"+"、"-"、"*"
  35. mt1.start();
  36. mt2.start();
  37. mt3.start();//交错输出"+"、"-"、"*"
  38. }
  39. }

通过实现Runnable接口来实现多线程

通过创建一个实现Runnable接口的类重写run()方法,然后创建该类的对象并作为参数传递给Thread类来新建Thread对象。

  1. 创建Runnable的实现类来重写run()方法
  2. 创建Runnable的实现类对象
  3. 新建Thread类对象,并将Runnable实现类对象作为其构造方法的参数

比起直接继承Thread来实现多线程相比,这个类还可以继承其他类

同一个Runnable实现类对象作为参数传递给多个线程(多个线程执行同样的操作)

  1. public class MyRunnable implements Runnable {
  2. @Override
  3. public void run() {
  4. for(int i=0; i<100; i++) {
  5. System.out.println(Thread.currentThread().getName()+":"+i);
  6. }
  7. }
  8. }
  9. public class MyRunnableDemo {
  10. public static void main(String[] args) {
  11. //创建MyRunnable类的对象
  12. MyRunnable my = new MyRunnable();//MyRunnable类可以看做给所有线程的一个资源
  13. /*
  14. 1.创建Thread类的对象,把MyRunnable对象作为构造方法的参数
  15. Thread(Runnable target)
  16. */
  17. //Thread t1 = new Thread(my);
  18. //Thread t2 = new Thread(my);
  19. /*
  20. 2.Thread(Runnable target, String name)
  21. */
  22. Thread t1 = new Thread(my,"高铁");
  23. Thread t2 = new Thread(my,"飞机");
  24. //启动线程
  25. t1.start();
  26. t2.start();
  27. }
  28. }

不同的Runnable实现类对象作为参数传递给多个线程(多个线程执行不同的操作)

创建Thread类对象的时候使用了Lambda表达式。

  1. public class test {
  2. public static void main(String[] args) {
  3. Thread t1 = new Thread(() -> {
  4. int i = 0;
  5. while (i < 100) {
  6. System.out.println("+");
  7. i++;
  8. }
  9. }, "高铁");
  10. Thread t2 = new Thread(() -> {
  11. int i = 0;
  12. while (i < 100) {
  13. System.out.println("-");
  14. i++;
  15. }
  16. }, "飞机");
  17. t1.start();
  18. t2.start();
  19. }
  20. }

Lambda表达式