Java多线程的三种开启方式

  1. 继承自Thread重写run方法
     public class MyThread extends Thread {
    
         @Override
         public void run() {
             System.out.println(getName());
             String name = getName();
             for (int i = 0; i < 20; i++) {
                 System.out.println(name + "---" + i);
             }
         }
     }
    
  2. 实现Runable接口及run方法
     public class RunableImp implements Runnable {
    
         @Override
         public void run() {
             String name = Thread.currentThread().getName();
             for (int i = 0; i < 20; i++) {
                 System.out.println(name + "---" + i);
             }
         }
     }
    
  3. 匿名内部类实现run方法
     // Runable匿名
     Thread thread1 = new Thread(new Runnable() {
         @Override
         public void run() {
             String name = Thread.currentThread().getName();
             for (int i = 0; i < 20; i++) {
                 System.out.println(name + "---" + i);
             }
         }
     });
     thread1.start();
     // Thread匿名
     new Thread() {
         @Override
         public void run() {
             String name = Thread.currentThread().getName();
             for (int i = 0; i < 20; i++) {
                 System.out.println(name + "---" + i);
             }
         }
     }.start();
    

Leave a Reply