java线程学习1
java实现多线程有三种方式:继承Thread类,重写run方法,启动使用start;实现runnable接口,重写run方法;实现callable接口,重写call方法(可以有返回值,也可以抛出异常)
1.多线程实现文件下载 利用FileUtils.copyURLtoFile()
package threadStudy; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.apache.commons.io.FileUtils; public class WebDownload { public void download(String url,String dest) { try { FileUtils.copyURLToFile(new URL(url), new File(dest)); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("url is error!"); } } }
package threadStudy; public class ThreadDownload extends Thread{ String url; String dest; public ThreadDownload(String url,String dest) { this.url = url; this.dest = dest; } @Override public void run() { new WebDownload().download(url, dest); System.out.println(dest); } public static void main(String[] args) { ThreadDownload t1 = new ThreadDownload("http://pic-bucket.ws.126.net/photo/0001/2019-06-06/EH0TSVI400AP0001NOS.jpg", "linzhiling.jpg"); ThreadDownload t2 = new ThreadDownload("http://pic-bucket.ws.126.net/photo/0001/2019-06-06/EH0TSVI500AP0001NOS.jpg", "linzhiling2.jpg"); ThreadDownload t3 = new ThreadDownload("http://pic-bucket.ws.126.net/photo/0001/2019-06-05/EGTO1O6800AN0001NOS.jpg", "rocket.jpg"); ThreadDownload t4 = new ThreadDownload("http://pic-bucket.ws.126.net/photo/0001/2019-06-05/EGTLGCTO00AN0001NOS.jpg", "rocket2.jpg"); t1.start(); t2.start(); t3.start(); t4.start(); } }
模拟抢票(同步问题以后解决)
package threadStudy; public class Tickets implements Runnable { /** * 使用runnable 实现线程 有利于共享资源 */ private int ticketNumber = 100; @Override public void run() { while (true) { if (ticketNumber <= 0) { break; } else { try { Thread.sleep(100); //模拟线程同步问题 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "----->" + ticketNumber--); } } } public static void main(String[] args) { Tickets t = new Tickets(); System.out.println(Thread.currentThread().getName()); new Thread(t,"黄牛一").start(); new Thread(t,"黄牛二").start(); new Thread(t,"黄牛三").start(); } }