一、通过继承Thread类来创建线程
1. 创建线程方式一 class MyThread extends Thread{ @Override public void run() { System.out.println("hello,thread!"); } } public class Demo01 { public static void main(String[] args) { Thread t = new MyThread(); t.start(); } } //根据此方式实现多线程并发执行 public class Demo02 { public static void main(String[] args) throws InterruptedException { Thread t = new MyThread2(); t.start(); while(true){ System.out.println("主线程"); Thread.sleep(1000);//使线程暂时阻塞,该时间段内线程不会上CPU } } } class MyThread2 extends Thread{ @Override public void run() { while(true){ System.out.println("子线程"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
二、创建一个类实现Runnable接口来创建线程
2. 创建线程方式二 public class Demo03 { public static void main(String[] args) { Thread t = new Thread(new MyRunnable()); t.start(); } } class MyRunnable implements Runnable{ @Override public void run() { System.out.println("子线程"); } }
三、使用匿名内部类来创建线程
3.创建线程方式三 public class Demo04 { public static void main(String[] args) { Thread t = new Thread(){ @Override public void run() { System.out.println("子线程"); } }; t.start(); } }
4.创建线程方式四 public class Demo05 { public static void main(String[] args) { Thread t = new Thread(new Runnable() { @Override public void run() { System.out.println("子线程"); } }); t.start(); } }
四、使用Lambda表达式来创建线程
5.创建线程方式五 public class Demo06 { public static void main(String[] args) { Thread t = new Thread(()->{ System.out.println("子线程"); }); t.start(); } }