下列代码利用继承Thread类实现线程的创建,运行结果如下图所示。根据运行结果利用实现Runnable接口的任务类、匿名类和Lambda表达式改写下面的代码实现相同的功能。 public class ThreadDemo extends Thread { public void run() { for (int i = 0; i < 100; i++) { // 继承Thread类时,直接使用this即可获取当前线程对象 // 调用getName()方法返回当前线程的名字 System.out.println(this.getName() + " : " + i); } } public static void main(String[] args)throws Exception { ThreadDemo td = new ThreadDemo(); td.start(); td.join(); // 主线程任务 for (int i = 1000; i < 1100; i++) { // 使用Thread.currentThread().getName()获取主线程名字 System.out.println(Thread.currentThread().getName() + " : " + i); } } }
时间: 2024-02-10 07:08:08 浏览: 145
Java中继承thread类与实现Runnable接口的比较
5星 · 资源好评率100%
使用实现Runnable接口的任务类改写代码如下:
```
public class RunnableDemo implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
public static void main(String[] args) throws Exception {
RunnableDemo rd = new RunnableDemo();
Thread t = new Thread(rd);
t.start();
t.join();
for (int i = 1000; i < 1100; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
}
```
使用匿名类改写代码如下:
```
public class AnonymousDemo {
public static void main(String[] args) throws Exception {
Thread t = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
});
t.start();
t.join();
for (int i = 1000; i < 1100; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
}
```
使用Lambda表达式改写代码如下:
```
public class LambdaDemo {
public static void main(String[] args) throws Exception {
Thread t = new Thread(() -> {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
});
t.start();
t.join();
for (int i = 1000; i < 1100; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
}
```
阅读全文