常见线程创建方式

文章目录

    • Thread 类
    • Runable 类
    • Callable 类

Thread 类

  • 继承Runable
  • 重写run() 函数,
  • 创建线程对象,调用start()方法启动线程
  • 不建议使用:避免OOP单继承局限性

Runable 类

  • 继承Callable 类
  • 创建线程对象,调用start()方法启动线程
  • 推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
import org.apache.commons.io.FileUtils;

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

public class TestThread2 implements Runnable {
    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 t1 = new TestThread2("https://s1.hdslb.com/bfs/static/jinkela/long/bitmap/error_01.png", "1.png");
        TestThread2 t2 = new TestThread2("https://s1.hdslb.com/bfs/static/jinkela/long/bitmap/error_01.png", "2.png");
        TestThread2 t3 = new TestThread2("https://s1.hdslb.com/bfs/static/jinkela/long/bitmap/error_01.png", "3.png");
        t1.run();
        t2.run();
        t3.run();
    }

}

class WebDownloader {
    public void downloader(String url, String name) {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            System.out.println("IO ERROR");
            e.printStackTrace();
        }
    }
}

Callable 类

  • 实现Callable接口,需要返回值类型(常见返回类型为Boolean)
  • 重写call方法,需要抛出异常(类似于run() 函数)
  • 创建目标对象
  • 创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);
  • 提交执行:Future result1 = ser.submit(t1);
  • 获取结果:boolean r1 = result1.get()
  • 关闭服务:ser.shutdownNow();
import org.apache.commons.io.FileUtils;

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

public class TestCallable implements Callable<Boolean> {
    private String url;
    private String name;

    public TestCallable() {
    }

    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 t1 = new TestCallable("https://s1.hdslb.com/bfs/static/jinkela/long/bitmap/error_01.png", "1.png");
        TestCallable t2 = new TestCallable("https://s1.hdslb.com/bfs/static/jinkela/long/bitmap/error_01.png", "2.png");
        TestCallable t3 = new TestCallable("https://s1.hdslb.com/bfs/static/jinkela/long/bitmap/error_01.png", "3.png");
        //创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(3);
        //提交执行
        Future<Boolean> r1=ser.submit(t1);
        Future<Boolean> r2=ser.submit(t2);
        Future<Boolean> r3=ser.submit(t3);
        //获取结果
        System.out.println(r1.get());
        boolean rs2 = r2.get();
        boolean rs3 = r3.get();
        //关闭服务
        ser.shutdown();
    }
}

class WebDownloader {
    public void downloader(String url, String name) {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (Exception e) {
            System.out.println("IO ERROR");
            e.printStackTrace();
        }
    }
}

龟兔赛跑案例:

public class Race implements Runnable {
    private static String wineer;

    @Override
    public void run() {
        if (Thread.currentThread().getName() == "兔子") {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for (int i = 0; i <= 100; ++i) {
            boolean flag = gameOver(i);
            if (flag == true) break;
            System.out.println(Thread.currentThread().getName()  + "跑了" + i + "步");
        }
    }

    private boolean gameOver(int steps) {
        if (wineer != null) {
            return true;
        } else {
            if (steps >= 100) {
                wineer = Thread.currentThread().getName();
                System.out.println("winner:" + wineer);
                return true;
            }
        }
        return false;
    }

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

    }
}

你可能感兴趣的:(Java,java)