// Java线程示例代码
// 创建线程的方式1:继承Thread类
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running, count: " + i);
}
}
}
// 创建线程的方式2:实现Runnable接口
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running, count: " + i);
}
}
}
public class ThreadExample {
public static void main(String[] args) {
// 方式1:继承Thread类
MyThread thread1 = new MyThread();
thread1.start();
// 方式2:实现Runnable接口
Thread thread2 = new Thread(new MyRunnable());
thread2.start();
// 使用匿名内部类创建线程
Thread thread3 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running, count: " + i);
}
});
thread3.start();
// 使用Lambda表达式创建线程
Thread thread4 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running, count: " + i);
}
});
thread4.start();
}
}
继承Thread类:
MyThread
类继承了 Thread
类,并重写了 run()
方法。main
方法中,通过 new MyThread().start()
启动线程。实现Runnable接口:
MyRunnable
类实现了 Runnable
接口,并实现了 run()
方法。main
方法中,通过 new Thread(new MyRunnable()).start()
启动线程。匿名内部类:
new Thread()
中定义 run()
方法。Lambda表达式:
以上代码展示了四种创建和启动线程的方式,每种方式都有其适用场景。
上一篇:java 字符串 正则判断包含
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站