1. 继承 Thread, 重写 run
public class Demo1 {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
//继承Thread,创建线程
class MyThread extends Thread{
@Override
public void run() {
System.out.println("这是zjm创建的继承自Thread的线程");
}
}
2. 实现 Runnable, 重写 run
public class Demo2 {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
//创建线程,并将myRunnable作为参数传入
Thread thread = new Thread(myRunnable);
thread.start();
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
while (true) {
System.out.println("这是zjm创建的实现了Runnable接口的线程");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
3. 继承 Thread, 重写 run, 使用匿名内部类
public class Demo3 {
public static void main(String[] args) {
Thread thread = new Thread(){
@Override
public void run() {
while (true) {
System.out.println("这是zjm创建的继承Thread,重写run,使用匿名内部类的创建线程的方式");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
thread.start();
}
}
4. 实现 Runnable, 重写 run, 使用匿名内部类
public class Demo4 {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println("这是zjm实现的 实现Runnable接口,重写Run,使用匿名内部类的创建现成的方式");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
}
5. 使用 lambda 表达式
public class Demo5 {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
while(true) {
System.out.println("这是zjm实现的通过lambda表达式创建线程的方式");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}