When I was reading the book "Thinking in JAVA", I found a question about JAVA multithreading.
class ThreadMethod {
private int countdown = 5;
private Thread t;
private String name;
public ThreadMethod(String name) {
this.name = name;
}
public void runTask() {
if (t == null) {
t = new Thread(name) {
public void run() {
while (true) {
System.out.println(this);
if (--countdown == 0) return;
try {
sleep(10);
} catch (InterruptedException e) {
System.out.println("interrupted");
}
}
}
public String toString() {
return getName() + ": " + countdown;
}
};
t.start();
}
}
}
public class ThreadVarations{
public static void main(String[] args) {
for(int i=0;i<10;i++)
new ThreadMethod("ThreadMethod").runTask();
}
}
The class ThreadMethod doesn't extends Thread
and implements Runnable
. So the class how to create a process?
您需要使用实现Runnable的给定类来启动新线程,并在其上调用start,方法run()
将在另一个线程中调用。
new Thread(new ThreadMethod).start();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.