下载图片
使用common-io-2.2 jar包下载图片
- 先下载jia包,
- 解压后粘贴到当前目录下,
- 在将其添加到类库中就可以使用了
package ThreadDemo;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//联系Thread实现多线程同步下载图片
public class ThreadDemo01 extends Thread {
private String url; //网络图片的地址
private String name;//保存的文件名
public ThreadDemo01(String url, String name) {
this.url = url;
this.name = name;
}
//下载图片线程的执行体
@Override
public void run() {
webDownLoader web=new webDownLoader();
web.downloader(url,name);
System.out.println("下载了文件名为"+name);
}
public static void main(String[] args) {
ThreadDemo01 th1=new ThreadDemo01("https://img2.baidu.com/it/u=1814268193,3619863984&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1658682000&t=d20c88a4eebf882f4f8950f8613ac1b4","n.jpg");
ThreadDemo01 th2=new ThreadDemo01("https://img2.baidu.com/it/u=1814268193,3619863984&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1658682000&t=d20c88a4eebf882f4f8950f8613ac1b4","m.jpg");
ThreadDemo01 th3=new ThreadDemo01("https://img2.baidu.com/it/u=1814268193,3619863984&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1658682000&t=d20c88a4eebf882f4f8950f8613ac1b4","p.jpg");
th1.start();
th2.start();
th3.start();
}
//下载器
class webDownLoader {
//下载方法
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常"+"downLoader出现问题");
}
}
}
}
Runnable接口的使用
- 实现接口Runnable具有多线程能力
- 启动线程:传入对象+Thread对象.start();
- 推荐使用:避免了单继承的局限性,灵活方便,方便同一个对象被多个线程使用
package RunnableStudy;
//创建线程方式二:实现Runnable接口,重写run方法,指向线程需要丢入runnable接口实现类
//调用start
public class Demo01 implements Runnable{
public static void main(String[] args) {
//创建runnable接口的实现类对象
Demo01 demo=new Demo01();
//创建线程对象,通过线程对象来开启我们的线程
// Thread thread = new Thread(demo);
// thread.start();
//两行结合
new Thread(demo).start();
for (int i = 0; i < 1200; i++) {
System.out.println("我在听歌");
}
}
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("我在学习");
}
}
}
龟兔赛跑
package RunnableStudy;
public class Race implements Runnable {
private static String winner;
public static void main(String[] args) {
Race race=new Race();
new Thread(race,"乌龟").start();
new Thread(race,"兔子").start();
}
@Override
public void run() {
for (int i = 0; i <=100; i++) {
//模拟兔子休息
if (Thread.currentThread().getName().equals("兔子")&&i%10==0){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断比赛是否结束
boolean flag=GameOver(i);
//比赛结束了停止程序
if(flag){
break;
}
System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
}
}
private boolean GameOver(int steps){
//判断是否有胜利者
if(winner!=null){//已经存在胜利者,比赛结束
return true;
}else if(steps>=100){
winner=Thread.currentThread().getName();
System.out.println("获胜者是"+winner);
return true;
}
return false;
}
}