[LeetCode] 1162. As Far from Land as Possible
阿新 • • 發佈:2021-12-05
繼承Thread類
public class TestThread extends Thread{ private String url; private String name; public TestThread(String url,String name){ this.url = url; this.name = name; } @Override public void run() { WebDownloadPic webDownloadPic = new WebDownloadPic(); webDownloadPic.downLoadPic(url,name); } public static void main(String[] args) throws InterruptedException { TestThread thread1 = new TestThread("http://192.168.11.140:8085/pictures/picOne.png","1.jpg"); TestThread thread2 = new TestThread("http://192.168.11.140:8085/pictures/picTwo.png","2.jpg"); TestThread thread3 = new TestThread("http://192.168.11.140:8085/pictures/picOne.png","3.jpg"); thread2.start(); thread2.join(); thread1.start(); thread1.join(); thread3.start(); } } class WebDownloadPic{ // 下載方法 public void downLoadPic(String url,String name){ try { FileUtils.copyURLToFile(new URL(url),new File(name)); System.out.println(Thread.currentThread().getName() + ":下載圖片:" + name); System.out.println(); } catch (IOException e) { e.printStackTrace(); } } }
實現Runnable介面
與Thread的區別就是:實現Runnable介面可以一個物件跑多執行緒
public class TestRunable implements Runnable{ private String name; public TestRunable(String name){ this.name = name; } @Override public void run() { Test test = new Test(); test.print(name); } public static void main(String[] args) { // ABC為執行緒名稱 TestRunable t1 = new TestRunable("A"); TestRunable t2 = new TestRunable("B"); TestRunable t3 = new TestRunable("C"); // new Thread(t1,"A").start(); new Thread(t1).start(); new Thread(t3).start(); new Thread(t2).start(); } } class Test{ public void print(String name){ for(int i = 0 ; i < 100 ; i ++){ System.out.println(Thread.currentThread().getName() + "列印了:" + name); } } }