[JavaSE学习之旅]线程创建的三种方式

线程创建

继承Thread类

Thread是实现Runable接口的

  • 自定义线程类继承Thread类

  • 重写run()方法,编写线程执行体

  • 创建线程对象,调用start()方法启动线程

    不推荐使用:避免OOP单继承局限性

public class TestThread extends Thread{

    @Override
    public void run(){
        for (int i = 0; i < 20; i++) {
            System.out.println("子线程"+i);
        }
    }

    public static void main(String[] args) {

        TestThread thread = new TestThread();

        thread.start();

        for (int i = 0; i < 2000; i++) {
            System.out.println("主线程"+i);
        }
    }
}

运行结果:

在这里插入图片描述

网图下载

import org.apache.commons.io.FileUtils;

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

//网图下载
public class TestThread2 extends Thread{

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

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

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

    public static void main(String[] args) {
        TestThread2 t1 = new TestThread2("http://www.zlcloud.design:8888/images/head/a16ec2da9d5c4c1c85214205eb4157dc.jpg","炮姐1.jpg");
        TestThread2 t2 = new TestThread2("http://www.zlcloud.design:8888/images/congress/ce4d53da38384cef9ed26cf17c0b2c63.jpg","炮姐2.jpg");
        TestThread2 t3 = new TestThread2("http://www.zlcloud.design:8888/images/congress/0.jpg","炮姐3.jpg");

        t1.start();
        t2.start();
        t3.start();
    }
}

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

运行结果

在这里插入图片描述

总结:线程直接是“同时”运行的,CPU调度安排

实现Runable接口

  • 定义MyRunable类实现Runable接口

  • 实现run()方法,编写线程执行体

  • 创建线程对象,调用start()方法启动线程

    推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用

public class TestThread3 implements Runnable{
    @Override
    public void run(){
        for (int i = 0; i < 20; i++) {
            System.out.println("子线程"+i);
        }
    }

    public static void main(String[] args) {

        TestThread3 testThread3 = new TestThread3();

        new Thread(testThread3).start();

        for (int i = 0; i < 2000; 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(10);
                } 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;
        }else{
            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();
    }
}

实现Callable接口

  1. 实现Callable接口,需要返回值类型

  2. 重写call方法,需要抛出异常

  3. 创建目标对象

  4. 创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);

  5. 提交执行:Future result1 = ser.submit(t1);

  6. 获取结果: boolean r1 = result1.get();

  7. 关闭服务: ser.shutdownNow();

    修改Thread网图下载的实现为Callable

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

public class TestCallable implements Callable<Boolean> {
    private String url;//网络图片地址
    private String name;//保存的文件名

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

    @Override
    public Boolean call() {
        WebDownloader1 webDownloader = new WebDownloader1();
        webDownloader.download(url,name);
        System.out.println("下载了文件名为:"+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable("http://www.zlcloud.design:8888/images/head/a16ec2da9d5c4c1c85214205eb4157dc.jpg","炮姐1.jpg");
        TestCallable t2 = new TestCallable("http://www.zlcloud.design:8888/images/congress/ce4d53da38384cef9ed26cf17c0b2c63.jpg","炮姐2.jpg");
        TestCallable t3 = new TestCallable("http://www.zlcloud.design:8888/images/congress/0.jpg","炮姐3.jpg");


        //创建执行服务:创建三个线程
        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();

        //关闭服务
        ser.shutdownNow();
    }
}
//加载器
class WebDownloader1{
    //下载方法
    public void download(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常");
        }
    }
}

让我们一起变得更强

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值