[Java]Three ways to implements Thread
1. extends Class Thread
- define Myclass that extends Thread
- override Run()
- new object to call start() to start thread. If call run() directly, it can’t be implemented concurrently, will be called by order. Start() will call run method concurrently.
public void start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
//example, create three threads to download pic from specificate URL concurrly
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class PictureDownloader extends Thread{
private String url;
private String name;
public PictureDownloader(String url, String name) {
this.url = url;
this.name = name;
}
@Override
public void run() {
try {
new Downloader().picDownloader(url,name);
System.out.println("download "+ name + "finished!\n");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] avrg){
PictureDownloader t1 = new PictureDownloader("https://img-blog.csdn.net/xx","1");
PictureDownloader t2 = new PictureDownloader("https://img-home.csdnimg.cn/images/xx4.gif","2");
PictureDownloader t3 = new PictureDownloader("https://avatar.csdnimg.cn/2/4/4/3xx.jpg","3");
//start
t1.start();
t2.start();
t3.start();
}
}
class Downloader {
public void picDownloader(String url, String name) throws IOException {
FileUtils.copyURLToFile(new URL(url),new File(name));
}
}
note: Class Thread is provided by jdk as core function in rt.jar java.lang package
details: https://docs.oracle.com/javase/8/docs/api/index.html
2. implements Runnable interface (recommendation)
- define Myclass implements Runnable interface
- override run() method
- new object of Myclass, take the object as parameter to new Thread and call start() methon. Thread plays as static agent.
//example, The Tortoise and the Hare
public class Race implements Runnable{
private static String winner;
@Override
public void run() {
for (int i = 0; i <=100; i++) {
boolean flag = gameOver(i);
if(flag){
break;
}
if(Thread.currentThread().getName() == "兔子" && i%10 == 0){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "跑了第" + i + "步\n");
}
}
private boolean gameOver(int steps){
if(winner != null){
return true;
}else {
if(steps == 100){
winner=Thread.currentThread().getName();
System.out.println("winner is"+ winner);
return true;
}
else {
return false;
}
}
}
public static void main(String[] avrg){
Race race = new Race();
new Thread(race,"兔子").start();
new Thread(race,"乌龟").start();
}
}