Java教程

初识java多线程

本文主要是介绍初识java多线程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

初识java多线程编程

多线程编程实现的三种方式

  1. Thread class 继承Thread类
  2. Runnable 接口 实现Runnable接口
  3. Callable 接口 实现Callable接口

继承Thread类(多线程下载图片)

public class ThreadDownload extends Thread {
    private String url;
    private String Filename;

    public ThreadDownload(String url, String filename) {
        this.url = url;
        this.Filename = filename;
    }

    //下载图片的线程执行数
    @Override
    public void run() {
        super.run();
        WebDownloader webDownloader = new WebDownloader();
        try {
            webDownloader.downLoader(url,Filename);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("下载的文件名:" + Filename);

        }

    }

    public static void main(String[] args) {
        ThreadDownload testThread01 = new ThreadDownload("https://www.baidu.com/img/baidu_jgylogo3.gif", "copy1.png");
        ThreadDownload testThread02 = new ThreadDownload("https://www.baidu.com/img/baidu_resultlogo@2.png", "copy2.png");
        ThreadDownload testThread03 = new ThreadDownload("https://www.baidu.com/img/bd_logo1.png", "copy3.png");
        System.out.println("========================");
        //理想状态是先下载t1,最后t2,最后t3
        //实质上是几乎同时执行,不一定是这个顺序
        testThread01.start();
        testThread02.start();
        testThread03.start();
    }
}

//下载器
class WebDownloader {
    //下载方法
    public void downLoader(String url, String filename) throws IOException {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(filename));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常");
        }
    }

}

实现Runnable接口(龟兔赛跑)

public class Race implements Runnable {

    //胜利者
    private static String winner;


    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            if (Thread.currentThread().getName().equals("兔子") && i == 60) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            boolean haswinner = gameOver(i);
            if (haswinner) {
                break;
            }
            System.out.println(Thread.currentThread().getName() + "跑了" + i + "步");
        }


    }

    //判断比赛是否结束
    private boolean gameOver(int steps) {
        if (winner != null) {
            System.out.println("赢家已经存在");
            return true;
        } else {
            if (steps >= 100) {
                winner = Thread.currentThread().getName();
                System.out.println("winner is " + winner);
                return true;
            } else {
                return false;
            }
        }

    }

    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race, "兔子").start();
        new Thread(race, "乌龟").start();

    }
}

实现Callable接口

public class TestCallable01 implements Callable<Boolean> {

    private String url;
    private  String Filename;


    public TestCallable01(String url,String Filename) {
        this.url = url;
        this.Filename = Filename;
    }

    @Override
    public Boolean call() throws Exception {
        WebDownloader  webDownloader = new WebDownloader();
        try {
            webDownloader.downLoader(url,Filename);
            System.out.println("下载的文件名不存在"+Filename);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable01 t1 = new TestCallable01("https://www.baidu.com/img/baidu_jgylogo3.gif","copy1.png");
        TestCallable01 t2 = new TestCallable01("https://www.baidu.com/img/baidu_resultlogo@2.png","copy2.png");
        TestCallable01 t3 = new TestCallable01("https://www.baidu.com/img/bd_logo1.png","copy3.png");

        //创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(3);

        //提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);

        //获取数据
        boolean rs1 = r1.get();
        boolean rs2 = r2.get();
        boolean rs3 = r3.get();

        System.out.println(rs1);
        System.out.println(rs2);
        System.out.println(rs3);
        //4:关闭服务
        ser.shutdown();

    }
}

class WebDownloader1 {
    //下载方法
    public void downLoader(String url, String filename) throws IOException {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(filename));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常");
        }
    }

}
这篇关于初识java多线程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!