线程实现方法

Thread类

  • 自定义线程类继承Thread类
  • 重写run()方法,编写线程执行体
  • 创建线程对象,调用start()发放启动线程

image-20230222082309025

package com.cz.demo4;

/**
 * @author 卓亦苇
 * @version 1.0
 */
public class TestThread1 extends Thread{
    @Override
    public void run() {
        //run方法线程题
        for (int i = 0; i < 30; i++) {
            System.out.println("run方法");
            
        }
    }

    public static void main(String[] args) {
        //创建线程对象
        TestThread1 testThread1 = new TestThread1();
        //调用start()方法开启线程,run()方法是按照顺序执行
        testThread1.start();

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

线程不一定执行,CPU执行调度单元

创建线程方式一:继承Tread类,重写run()方法,调用start开启线程

注意,线程开启不一定立即执行,由CPU调度执行

package com.cz.demo4;

import org.apache.commons.io.FileUtils;

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

/**
 * @author 卓亦苇
 * @version 1.0
 */
public class TestTread2 extends Thread{
    //练习Tread。实现多线程同步下载图片

    private String url;//照片地址
    private String file;//保存的文件名

    public TestTread2(String url,String file){
        this.url=url;
        this.file=file;
    }

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

    public static void main(String[] args) {
        TestTread2 testTread2 = new TestTread2();
        testTread2.start();
    }
}
//下载器
class WebDownloader{
    //下载方法
    public void downloader(String url,String file){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(file));
        } catch (IOException e) {
            System.out.println("IO异常,downloader方法出现问题");
        }
    }
}

实现Runnable接口

Thread也是通过Runnable接口来进行实现的

  • 定义MyRunnable类实现Runnable接口
  • 实现run()方法,编写线程执行体
  • 创建线程对象,调用start()方法启动线程
package com.cz.demo4;

/**
 * @author 卓亦苇
 * @version 1.0
 */
//创建线程方式2,实现runnable接口,重写run方法
public class TestThread3 implements Runnable {
    @Override
    public void run() {
        //run方法线程题
        for (int i = 0; i < 300; i++) {
            System.out.println("run方法");

        }
    }

    public static void main(String[] args) {
        //创建线程对象
          TestThread3 testThread3 = new TestThread3();
//        Thread thread = new Thread(testThread3);
//        //调用start()方法开启线程,run()方法是按照顺序执行
//        thread.start();
            new Thread(testThread3).start();
        //main线程,主线程
        for (int i = 0; i < 300; i++) {
            System.out.println("主线程");
        }
    }
}

继承Thread类

  • 子类继承Thread类具备多线程能力

  • 启动线程:子类对象. start()

  • 不建议使用:避免OOP单继承局限性

实现Runnable接口

  • 实现接口Runnable具有多线程能力

  • 启动线程:传入目标对象+Thread对象.start()

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

实例运用

龟兔赛跑

package com.cz.demo4;

/**
 * @author 卓亦苇
 * @version 1.0
 */
public class Race implements Runnable{
    private static String winner;

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

            System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
            boolean flag = win(i);
            if(flag){
                break;
            }
            if(Thread.currentThread().getName().equals("兔子") && i%10==0){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }
    //判断是否赢得比赛
    private boolean win(int stop){
        if(winner!=null){
            return true;
        }
        if(stop==100){
            winner=Thread.currentThread().getName();
            System.out.println("胜利者是"+winner);
            
            return true;
        }
        return false;
    }

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

实现Callable接口

image-20230222215903514

package com.cz.demo4;

import org.apache.commons.io.FileUtils;

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

/**
 * @author 卓亦苇
 * @version 1.0
 * 2023/2/22 21:22
 */
//callable好处,可以定义返回值,可以抛出异常
public class TestCallable implements Callable<Boolean> {
    private String url;
    private String file;

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

    }

    @Override
    public Boolean call() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.Downloader(url, file);
        System.out.println("下载文件名为" + file);
        return true;
    }

    public static void main(String[] args) {
        TestCallable TC1 = new TestCallable("", "");
        TestCallable TC2 = new TestCallable("", "");
        TestCallable TC3 = new TestCallable("", "");
        //创建执行服务,括号内为线程个数
        ExecutorService ser = Executors.newFixedThreadPool(3);

        //提交执行
        Future<Boolean> r1 = ser.submit(TC1);
        Future<Boolean> r2 = ser.submit(TC2);
        Future<Boolean> r3 = ser.submit(TC3);
        //获取结果
        try {
            boolean rs1 = r1.get();
            boolean rs2 = r2.get();
            boolean rs3 = r3.get();

        } catch (Exception e) {
            throw new RuntimeException(e);

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

class WebDownloader{
    public void Downloader(String url,String file){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(file));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
posted @   卓亦苇  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
点击右上角即可分享
微信分享提示