Loading

Java多线程02-法1继承Thread类

02、继承Thread类

  • 自定义线程类继承Thread
  • 重写run()方法,编写线程执行体
  • 创建线程对象,调用start()开启线程

代码演示

//创建线程的方式一:继承Thread类,重写run()方法,调用start开启线程
//线程开启不一定立即执行,由cpu决定
public class TestThread1 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("我在看代码!!!!!!!!!!!!!!!!!!");
        }
    }

    public static void main(String[] args) {
        TestThread1 testThread1=new TestThread1();
        testThread1.start();
        for (int i = 0; i < 10; i++) {
            System.out.println("我在学习多线程---");
        }
    }
}

实现多线程同步下载图片

代码演示

public class TestThread2 extends Thread{
    private String url;
    private String name;

    public TestThread2(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) {
        TestThread2 testThread201=new TestThread2("http://8.136.39.89:9090/asserts/img/portfolio-1.jpg","portfolio-1.jpg");
        TestThread2 testThread202=new TestThread2("http://8.136.39.89:9090/asserts/img/portfolio-2.jpg","portfolio-2.jpg");
        TestThread2 testThread203=new TestThread2("http://8.136.39.89:9090/asserts/img/portfolio-3.jpg","portfolio-3.jpg");
        testThread201.start();
        testThread202.start();
        testThread203.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异常,downder出现问题");
        }
    }
}
posted @ 2022-02-12 23:53  Cn_FallTime  阅读(30)  评论(0编辑  收藏  举报