de路过人间

一个想努力学编程变成大神的女孩子。

Java多线程

多线程

网图下载

package com.jinjin.www.demo3;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

public class TextThread2  extends Thread{
    private String url;
    private String name;
    public TextThread2(String url,String name) {
        this.url=url;
        this.name=name;
    }



    @Override
    public void run() {
        WebDownloader webDownloader=new WebDownloader();
        WebDownloader.downloader(url,name);
        System.out.println("下载了文件名为:"+name);
    }

    public static void main(String[] args) {
        TextThread2 t1= new TextThread2("https://www.htu.edu.cn/_upload/article/images/be/e2/dd3b923c48aa9b44e97cec4254ed/4ec1779e-bf60-4d49-8cc8-336c74d711b4.jpg","1,jpg");
        TextThread2 t2= new TextThread2("https://www.htu.edu.cn/_upload/article/images/26/ef/95dae5b246d6a48c0ece8a3ae14b/9033e20e-68a4-4961-9769-f5a5fb59cbbd.jpg","2,jpg");
        TextThread2 t3= new TextThread2("https://www.htu.edu.cn/_upload/article/images/47/12/367a35644989be1f0fbfd179cb1a/2af69057-046c-47c3-894b-ee43b78a3c77_s.jpg","3,jpg");
        t1.start();
        t2.start();
        t3.start();
    }
}
//下载器
class WebDownloader {
    //下载方法
    public static 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方法出现问题");
        }
    }
}

并发问题

package com.jinjin.www.demo3;
//发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱。
public class TextThread4 implements Runnable {
    private int ticketNums=10;
    @Override
    public void run() {
        while(true){
            if(ticketNums<=0){
                break;
            }
//模拟延时
            try {
                Thread.sleep(200);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"票");
        }
    }

    public static void main(String[] args) {
        TextThread4 ticket=new TextThread4();
        new Thread(ticket,"小明").start();
        new Thread(ticket,"老师").start();
        new Thread(ticket,"黄牛").start();
    }
}
image-20201109132230017

posted on 2020-11-17 21:53  de路过人间  阅读(220)  评论(0编辑  收藏  举报

导航