线程的创建之实现Runnable接口

建议使用,避免单继承局限性,灵活方便,方便同一对象被多个线程同时使用。

1. 过程

  1. 实现Runnable接口。
  2. 重写run方法。
  3. 执行线程需要丢入Runnable接口实现类,调用start()方法。

2. 使用

public class Demo3 implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 200; i++) {
            System.out.println(i + "run");
        }
    }

    public static void main(String[] args) {
        // 通过代理方式启动
        new Thread(new Demo3()).start();

        for (int i = 0; i < 200; i++) {
            System.out.println(i + "main");
        }
    }
}

3. 利用多线程下载网图

public class Demo4 implements Runnable {

    private String url;
    private String name;

    public Demo4(String url, String name) {
        this.url = url;
        this.name = name;
    }

    @Override
    public void run() {
        new WebDownloader().downloader(url,name);
    }

    public static void main(String[] args) {
        new Thread(new Demo2("https://cdn.jsdelivr.net/gh/rootwhois/oss@main/uPic/image-20210820235038265.png", "1.png")).start();
        new Thread(new Demo2("https://cdn.jsdelivr.net/gh/rootwhois/oss@main/uPic/image-20210820235038265.png", "2.png")).start();
        new Thread(new Demo2("https://cdn.jsdelivr.net/gh/rootwhois/oss@main/uPic/image-20210820235038265.png", "3.png")).start();
    }
}

class WebDownloader2 {
    public void downloader(String path, String name){
        try {
            FileUtils.copyURLToFile(new URL(path), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4. 小案例

龟兔赛跑

public class Race implements Runnable{

    private static String winner;

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            if (hasWinnder(i)) {
                break;
            }

            // 模拟兔子睡觉
            if (Thread.currentThread().getName().equals("兔子") && i % 10 == 0) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println(Thread.currentThread().getName() + "跑了第" + i + "步");
        }
    }

    private boolean hasWinnder(int i){
        if (winner != null){
            return true;
        } else {
            if (i >= 100) {
                winner = Thread.currentThread().getName();
                System.out.println(winner + "胜利");
                return true;
            }
        }
        return false;
    }


    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race, "兔子").start();
        new Thread(race, "乌龟").start();
    }
}
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2023-03-05 10:55:52

results matching ""

    No results matching ""