java线程创建的三种方式

1. 继承Thread

//创建线程方式1:继承Thread类,重写run() 方法,调用start开启线程
public class TestThread01 extends Thread {

    public static void main(String[] args) {

        //创建一个线程对象
        TestThread01 testThread01 = new TestThread01();
        testThread01.start(); //自动调用run方法

        //main线程,主线程
        for (int i = 0; i < 20; i++) {
            System.out.println("我在学习多线程---"+i);
        }
    }

    @Override
    public void run() {
        //run方法线程体
        for (int i = 0; i < 20; i++) {
            System.out.println("我在run方法里面执行---"+i);
        }
    }
}

案例:下载网络资源
需要commonsio包
commonsio

import org.apache.commons.io.FileUtils;

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

public class TestThread02 extends Thread{
    private String url;
    private String name;

    public TestThread02(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) {
        TestThread02 t1 = new TestThread02("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1597676380539&di=7dd6c3dcd878c3233c136e4e33bfba89&imgtype=0&src=http%3A%2F%2Fpic.jj20.com%2Fup%2Fallimg%2Fmx02%2F06191R25237%2F1P619225237-2.jpg", "AngelaZhang1.jpg");
        TestThread02 t2 = new TestThread02("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1597676474938&di=f69a669886f66abe9efed24b76ca65f1&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fpic%2Fc%2F1d%2Fa46b8b5d35_250_350.jpg", "AngelaZhang2.jpg");
        TestThread02 t3 = new TestThread02("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3341717273,1859276094&fm=26&gp=0.jpg", "AngelaZhang3.jpg");
        t1.start();
        t2.start();
        t3.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 TestThread03 implements Runnable {

    public static void main(String[] args) {
        //创建一个Runnable接口实现类的实体
        TestThread03 testThread03 = new TestThread03();
        //创建线程对象,通过线程对象开启线程,代理
        new Thread(testThread03).start();


        //main线程,主线程
        for (int i = 0; i < 20; i++) {
            System.out.println("我在学习多线程---"+i);
        }
    }

    @Override
    public void run() {
        //run方法线程体
        for (int i = 0; i < 20; i++) {
            System.out.println("我在run方法里面执行---"+i);
        }
    }

}

案例:龟兔赛跑

public class Race implements Runnable {
    private static String winner;

    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {

            boolean flag = gameOver(i);
            if (flag){
                break;
            }

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

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

    }

    public 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接口:有返回值并且可以抛出异常

import org.apache.commons.io.FileUtils;

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

//线程创建方式三;实现Callable接口

/*
有返回值
可以抛出异常
 */
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 Exception {
        TestCallable t1 = new TestCallable("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1597676380539&di=7dd6c3dcd878c3233c136e4e33bfba89&imgtype=0&src=http%3A%2F%2Fpic.jj20.com%2Fup%2Fallimg%2Fmx02%2F06191R25237%2F1P619225237-2.jpg", "AngelaZhang1.jpg");
        TestCallable t2 = new TestCallable("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1597676474938&di=f69a669886f66abe9efed24b76ca65f1&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fpic%2Fc%2F1d%2Fa46b8b5d35_250_350.jpg", "AngelaZhang2.jpg");
        TestCallable t3 = new TestCallable("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3341717273,1859276094&fm=26&gp=0.jpg", "AngelaZhang3.jpg");
		//线程的启动分为以下四步
        //1.执行服务
        ExecutorService service = Executors.newFixedThreadPool(3);
        //2.提交执行
        Future<Boolean> r1 = service.submit(t1);
        Future<Boolean> r2 = service.submit(t2);
        Future<Boolean> r3 = service.submit(t3);
        //3.获取结果
        Boolean rs1 = r1.get();
        Boolean rs2 = r2.get();
        Boolean rs3 = r3.get();
        //4.关闭服务
        service.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方法出现问题");
        }
    }
}
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class TestCallable2 {
    public static void main(String[] args) {
        FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread());
        new Thread(futureTask,"MyThread").start();
        try {
            Integer integer = futureTask.get();
            System.out.println(integer);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

class MyThread implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName());
        return 100;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值