带有Thread Class和Runnable接口的输出
这两个程序都说,两者都是用相同的逻辑实现的,即在一个程序中,通过扩展Thread类创建线程,并通过实现Runnable接口创建线程。
这里的输出将像“打印一些值,直到我按ENTER或RETURN键”,我的问题是,当我运行这两个程序“我们正在创建线程通过扩展线程类的程序将停止扩展线程类打印值直到我按ENTER / RETURN但是“程序中我们说的都是创建带有Runnable接口输出的线程正在停止”
这两个程序中的逻辑是相同的,唯一不同的是扩展Thread类和实现Runnable接口的程序不同。
通过扩展主题
import java.io.IOException;
class TryThread extends Thread {
public TryThread(String firstName, String secondName, long delay) {
this.firstName = firstName;
this.secondName = secondName;
aWhile = delay;
setDaemon(true);
}
public void run() {
try {
while (true) {
System.out.print(firstName);
Thread.sleep(aWhile);
System.out.print(secondName + "n");
}
} catch (InterruptedException e) {
System.out.println(firstName + secondName + e);
}
}
private String firstName;
private String secondName;
private long aWhile;
}
public class Lab1 {
public static void main(String[] args) {
Thread first = new TryThread("A ", "a ", 200L);
Thread second = new TryThread("B ", "b ", 300L);
Thread third = new TryThread("C ", "c ", 500L);
System.out.println("Press Enter when you have had enough...n");
first.start();
second.start();
third.start();
try {
System.in.read();
System.out.println("Enter pressed...n");
} catch (IOException e) {
System.out.println(e);
}
return;
}
}
输出:
Press Enter when you have had enough...
A B C a
A b
B a
A c
C a
A b
B a
A b
B c
C a
A a
A b
B a
A c
C b
B a
A
Enter pressed...
通过实现可运行接口
import java.io.IOException;
class TryThread1 implements Runnable {
public TryThread1(String firstName, String secondName, long delay) {
this.firstName = firstName;
this.secondName = secondName;
aWhile = delay;
}
public void run() {
try {
while (true) {
System.out.print(firstName);
Thread.sleep(aWhile);
System.out.print(secondName + "n");
}
} catch (InterruptedException e) {
System.out.println(firstName + secondName + e);
}
}
private String firstName;
private String secondName;
private long aWhile;
}
public class Lab2 {
public static void main(String[] args) {
Thread first = new Thread(new TryThread1("A ", "a ", 200L));
Thread second = new Thread(new TryThread1("B ", "b ", 300L));
Thread third = new Thread(new TryThread1("C ", "c ", 500L));
System.out.println("Press Enter when you have had enough...n");
first.start();
second.start();
third.start();
try {
System.in.read();
System.out.println("Enter pressed...n");
} catch (IOException e) {
System.out.println(e);
}
return;
}
}
产量
Press Enter when you have had enough...
A B C a
A b
B a
A c
C a
A b
B a
A b
B c
C a
A a
A b
B a
A c
C b
B a
A a
A b
B c
C a
A
Enter pressed...
b
B a
A a
A b
B c
C a
A b
B a
A c
C a
A b
B a
A b
B a
A c
C a
A b
B a
A c
C b
B a
A a
A b
请告诉我扩展线程和实现Runnable接口的区别。 他们大多喜欢实现可运行接口。 但从这个产出差异来看,我不知道哪一个更喜欢
差异似乎是特定于您的代码。 你可以调用setDaemon(true) - JavaDoc - 当扩展Thread
时,而不是在实现Runnable
。 JavaDoc说:当运行的唯一线程都是守护进程线程时,Java虚拟机会退出。