继承Thread类 重写run方法
- Thread类也是Runnable接口的实现类
/** * @author 舒一笑 * @date 2023/5/24 */ public class test1 { public static void main(String[] args) { Thread01 thread01 = new Thread01(); thread01.start(); for (int i = 0; i < 100; i++) { System.out.println("mian" + i); } } } class Thread01 extends Thread{ @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println("Thread01" + i); } } }
实现Runnable接口 重写run方法
/** * @author 舒一笑 * @date 2023/5/24 */ public class test1 { public static void main(String[] args) { // Thread01 thread01 = new Thread01(); // thread01.start(); Thread02 thread02 = new Thread02(); Thread t2 = new Thread(thread02); t2.start(); for (int i = 0; i < 100; i++) { System.out.println("mian" + i); } } } class Thread01 extends Thread{ @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println("Thread01" + i); } } } class Thread02 implements Runnable{ @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println("Thread02" + i); } } }
匿名内部类方式:
/** * @author 舒一笑 * @date 2023/5/24 */ public class test1 { public static void main(String[] args) { // Thread01 thread01 = new Thread01(); // thread01.start(); // Thread02 thread02 = new Thread02(); // Thread t2 = new Thread(thread02); // t2.start(); // // for (int i = 0; i < 100; i++) { // System.out.println("mian" + i); // } Thread t3 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println("Thread03" + i); } } }); t3.start(); } } /**
lambda表达式的方式创建
/** * @author 舒一笑 * @date 2023/5/24 */ public class test1 { public static void main(String[] args) { // Thread01 thread01 = new Thread01(); // thread01.start(); // Thread02 thread02 = new Thread02(); // Thread t2 = new Thread(thread02); // t2.start(); // // for (int i = 0; i < 100; i++) { // System.out.println("mian" + i); // } // Thread t3 = new Thread(new Runnable() { // @Override // public void run() { // for (int i = 0; i < 10; i++) { // System.out.println("Thread03" + i); // } // } // }); Thread t4 = new Thread(() -> { for (int i = 0; i < 100; i++) { System.out.println("lambda:" + i); } }); t4.start(); } }
总结
启动线程是调用start方法,这样会创建一个新的线程,并执行线程的任务。
如果直接调用run方法,这样会让当前线程执行run方法中的业务逻辑。