多线程(三种创建方式)

一、多线程(三种创建方式

Thread class 继承Thread类(重点)

Runnable 接口 实现Runnable接口(重点)

Callable接口 实现Callable接口

1、Thread 类

/**
 * 1、创建线程方式 1:继承Thread类,重写 run()方法,调用start开启线程
 *
 * 总结:注意,线程开启不一定立即执行,由CPU调度执行
 */
public class TestThread1 extends Thread{
    
    

    @Override
    public void run() {
    
    
        // run 方法线程体
        for(int i=0;i<20;i++){
    
    
            System.out.println("我在学习:"+i);
        }
    }

    public static void main(String[] args){
    
    
        //main 线程 ,主线程
        //创建一个线程对象
        TestThread1 testThread1 = new TestThread1();
        //调用start()方法开启线程
        testThread1.start();

        for(int i=0;i<20;i++){
    
    
            System.out.println("我在学习多线程:"+i);
        }
    }
}
示例如下:

//练习Thread,实现多线程同步下载图片
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 test1 = new TestThread2("https://preview.qiantucdn.com/58pic/10/54/62/36858PICpec2fD34c858PIC8e_PIC2018.jpg!kuan320","1.jpg");
        TestThread2 test2 = new TestThread2("https://preview.qiantucdn.com/58pic/10/54/92/73e58PICfeAgnfth0e6pX_PIC2018.jpg!kuan320","2.jpg");
        TestThread2 test3 = new TestThread2("https://preview.qiantucdn.com/58pic/00/97/59/91X58PICw8vDFXXbz2G58PICK_PIC2018.jpg!kuan320","3.jpg");
        test1.start();
        test2.start();
        test3.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方法出现异常");
        }
    }
}

2、Runnable接口

/**
 * 创建线程方式2:实现 Runnable接口,重写 run() ,执行线程需要丢入runnable 接口实现类,调用start方法
 */
public class TestThread3 implements Runnable{
    
    

    @Override
    public void run() {
    
    
        // run 方法线程体
        for(int i=0;i<20;i++){
    
    
            System.out.println("我在学习:"+i);
        }
    }

    public static void main(String[] args){
    
    
        //创建Runnable接口的实现类对象
        TestThread3 testThread3 = new TestThread3();

//        //创建线程对象,通过线程对象来开启我们的线程,代理
//        Thread thread = new Thread(testThread3);
//        thread.start();

        new Thread(testThread3).start();


        for(int i=0;i<20;i++){
    
    
            System.out.println("我在学习多线程:"+i);
        }
    }
}
龟兔赛跑案例
/**
 * 龟兔赛跑案例
 */
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%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;
        }{
    
    
            if(steps >= 100){
    
    
                winner = Thread.currentThread().getName();
                System.out.println("winner is"+winner);
                return true;
            }
        }
        return  false;
    }

    public static void main(String[] args) {
    
    
        Race race = new Race();

        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();
    }
}

3、Callable接口

/**
 * 线程创建方式3:实现Callable 接口
 *
 * 优点:
 * 1、可以定义返回值
 * 2、可以抛出异常
 * */
public class TestCallable implements Callable<Boolean> {
    
    

    private String url;    //网络图片地址
    private String name;    //保存文件名

    //构造器
    public TestCallable(String url,String name){
    
    
        this.url=url;
        this.name=name;
    }

    /**
     * 下载图片线程的执行体
     */
    @Override
    public Boolean call() {
    
    
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url,name);
        System.out.println("下载了的文件名为:"+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
    
    
        TestCallable test1 = new TestCallable("https://preview.qiantucdn.com/58pic/10/54/62/36858PICpec2fD34c858PIC8e_PIC2018.jpg!kuan320","1.jpg");
        TestCallable test2 = new TestCallable("https://preview.qiantucdn.com/58pic/10/54/92/73e58PICfeAgnfth0e6pX_PIC2018.jpg!kuan320","2.jpg");
        TestCallable test3 = new TestCallable("https://preview.qiantucdn.com/58pic/00/97/59/91X58PICw8vDFXXbz2G58PICK_PIC2018.jpg!kuan320","3.jpg");

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

        //提交执行
        Future<Boolean> r1 = ser.submit(test1);
        Future<Boolean> r2 = ser.submit(test2);
        Future<Boolean> r3 = ser.submit(test3);

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

        System.out.println(rs1);
        System.out.println(rs2);
        System.out.println(rs3);

        //关闭服务
        ser.shutdownNow();
    }

}

//下载器
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方法出现异常");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/m0_59133441/article/details/119974391