s-day05-匿名内部类实现多线程(重点掌握)

This commit is contained in:
2026-08-06 10:14:25 +08:00
parent 2f134cad16
commit 8c0adb8143
@@ -0,0 +1,58 @@
package com.inmind.thread_noname03;
/*
匿名内部类的语法:
new 父类名|接口名(){
要重写的方法
}
匿名内部类的作用:将父类或者接口的子类(实现类)的定义和对象的创建用一段代码操作完毕
匿名内部类一定是多态
多线程的启动方式
1.继承Thread
2.实现Runnable
*/
public class Demo04 {
public static void main(String[] args) {
//普通写法,非匿名内部类(开启线程方式一:继承Thread)
/*MyThread myThread = new MyThread();
myThread.start();*/
System.out.println("-------------------------");
//匿名内部类启动线程,方式一
Thread thread = new Thread(){
@Override
public void run() {
System.out.println("匿名内部类启动了子线程:"+Thread.currentThread().getName());
}
};
thread.start();
//普通写法,非匿名内部类(开启线程方式二:实现Runnable)
//Thread thread = new Thread(myRunnable, "线程666");
//匿名内部类启动线程,方式二:实现Runnable
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("匿名内部类启动了子线程(Runnable):"+Thread.currentThread().getName());
}
});
thread1.start();
System.out.println("-----------匿名对象+匿名内部类写法--------------");
//方式一:继承Thread
new Thread(){
@Override
public void run() {
System.out.println("匿名对象+匿名内部类启动了子线程(继承Thread):"+Thread.currentThread().getName());
}
}.start();
//方式二:实现Runnable
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("匿名对象+匿名内部类启动了子线程(实现Runnable):"+Thread.currentThread().getName());
}
}).start();
}
}