线程的创建(Thread、Runnable、Callable)

1.Thread

1.1创建TestThread并继承 Thread 类

package com.sxh.demo1;

/**
 * @author 司小虎 E-mail:sxh100600@gmail.com
 * @version 创建时间:2020/1/1 11:30
 */
//创建线程方式-:继承Thread类,重写run()方法,调用start开启线程

    //总结:注意,线程开启不一定执行,有cpu调度执行
public class TestThread extends Thread{
    @Override
    public void run() {
        //run方法线程体
        for (int i = 0; i <200 ; i++) {
            System.out.println("我在看代码"+i);
        }
    }

    public static void main(String[] args) {
        //main线程,主线程

        //创建一个线程对象
        TestThread testThread = new TestThread();
        //调用start() 方法开启线程
        testThread.start();

        for (int i = 0; i <1000 ; i++) {
            System.out.println("我在学习多线程"+i);
        }
    }
}

控制台打印结果:

结论:两个线程同时在跑

简单的例子:下载图片

(1)导入 pom依赖
 <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
(2)创建TestThread类
//联系Thread ,实现多线程同步下载图片

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() {
        WebDownLoad wd=new WebDownLoad();
        wd.download(url,name);
        System.out.println("下载的文件名为"+name);

    }

    public static void main(String[] args) {
        TestThread02 testThread01 = new TestThread02("https://blog.kuangstudy.com/usr/themes/PureLoveForTypecho/images/banner1.jpg","1.jpg");
        TestThread02 testThread02 = new TestThread02("https://blog.kuangstudy.com/usr/themes/PureLoveForTypecho/images/banner2.jpg","2.jpg");
        TestThread02 testThread03 = new TestThread02("https://blog.kuangstudy.com/usr/themes/PureLoveForTypecho/images/banner3.jpg","3.jpg");
        testThread01.start();
        testThread02.start();
        testThread03.start();
    }

}

//下载器
class WebDownLoad{

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

}
(3)执行结果:说明他们是同时在下载

2.实现Runnable接口(推荐使用)

2.1定义MyRunable类实现Runnable接口

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

2.3创建线程对象,体哦也能够start()方法启动线程

///创建线程方法2:是实现Runnable接口,重写run方法,执行线程需要丢入runable接口实现类,调用start方法
public class MyRunable implements Runnable  {


    public void run() {
        //run方法线程体
        for (int i = 0; i < 200; i++) {
            System.out.println("你好坏---Runable--");
        }
    }


    public static void main(String[] args) {
        MyRunable myRunable = new MyRunable();

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

        for (int i = 0; i < 1000; i++) {
            System.out.println("我在学习多线程的--");
        }


    }

}

举个小例子:

//多个线程同时操作一个对象
    //买火车票的例子


    //发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱
public class TestThread4 implements Runnable{

    //票数
    private int ticket=10;


    public void run() {
        while(true){
            if (ticket<=0){
                break;
            }

            //模拟延时
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


            System.out.println(Thread.currentThread().getName()+"---》拿到了第"+ticket--+"票");

        }
    }


    public static void main(String[] args) {
        TestThread4 testThread4 = new TestThread4();
        new Thread(testThread4,"小明").start();
        new Thread(testThread4,"小红").start();
        new Thread(testThread4,"黄牛党").start();


    }

}

案例:龟兔赛跑

public class Race implements Runnable {
    //胜利者
    private static String winner;





    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){ //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();
    }



}

实现Callable 接口(现阶段 了解即可)

  1. 实现Callable接口,需要返回值类型
  2. 重写call方法,需要抛出异常
  3. 创建目标对象
  4. 创建执行服务:ExecutorService ser=Executors.newFixedThreadPool(1)
  5. 提交执行:Future<Boolean> result1=ser.submint(t1);
  6. 获取结果:boolean r1=result1.get()
  7. 关闭服务:ser。shutdownNow();

package com.sxh.demo1;

import org.apache.commons.io.FileUtils;

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

/**
 * @author 司小虎 E-mail:sxh100600@gmail.com
 * @version 创建时间:2020/1/3 9:58
 */
//线程创建方式三:实现calable接口
public class TestCallable implements Callable<Boolean> {
    private String url;   ///网络图片的地址
    private String name;  //保存的文件名

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


    ///下载图片线程的执行体
    public Boolean call() {
        WebDownLoad wd=new WebDownLoad();
        wd.download(url,name);
        System.out.println("下载的文件名为"+name);
    return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable testThread01 = new TestCallable("https://blog.kuangstudy.com/usr/themes/PureLoveForTypecho/images/banner1.jpg","1.jpg");
        TestCallable testThread02 = new TestCallable("https://blog.kuangstudy.com/usr/themes/PureLoveForTypecho/images/banner2.jpg","2.jpg");
        TestCallable testThread03 = new TestCallable("https://blog.kuangstudy.com/usr/themes/PureLoveForTypecho/images/banner3.jpg","3.jpg");
        //创建服务
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        //提交执行
        Future<Boolean> submit1 = executorService.submit(testThread01);
        Future<Boolean> submit2 = executorService.submit(testThread02);
        Future<Boolean> submit3 = executorService.submit(testThread03);
        //获取结果
        Boolean rs1 = submit1.get();
        Boolean rs2 = submit2.get();
        Boolean rs3 = submit3.get();

        //关闭服务
        executorService.shutdownNow();

    }

}

Last modification:February 6th, 2020 at 04:48 pm
如果觉得我的文章对你有用,请随意赞赏