Java教程

自学笔记-java多线程

本文主要是介绍自学笔记-java多线程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

目录

  • 1. 继承 Thread 类实现
  • 2. 实现Runnable接口
  • 3. 实现callable接口


1. 继承 Thread 类实现

① 继承Thread类
② 重写run()方法
③ 调用start()方法开启线程

package com.example.myjava.javaMultithreading;

/**
 * @Description: 多线程继承Thread类的实现
 * @Author: Hanzao
 * @Date: 2022/01/14/17:10
 */
public class LearnThread extends Thread{
    @Override
    public void run(){
        for(int i=0;i<100;i++){
            System.out.println("子线程输出了"+i+this.getName());
        }
    }

    public static void main(String[] args) {
        LearnThread thread1 = new LearnThread();
        thread1.start();
        LearnThread thread2 = new LearnThread();
        thread2.start();

        for(int i=0;i<10000;i++){
            System.out.println(">>主线程输出了"+i);
        }
    }
}

在这里插入图片描述

2. 实现Runnable接口

① 实现Runnable接口
② 重写run()方法
③ 执行线程需要丢入runnable接口实现类,调用start()方法

package com.example.myjava.javaMultithreading;

/**
 * @Description:
 * @Author: Hanzao
 * @Date: 2022/01/14/19:39
 */
public class LearnRunnable implements Runnable{
    @Override
    public void run() {
        for(int i=0;i<100;i++){
            System.out.println("子线程输出了:"+i+" "+Thread.currentThread().getName());
        }
    }

    public static void main(String[] args) {
        LearnRunnable learnRunnable = new LearnRunnable();
        new Thread(learnRunnable).start();
        new Thread(learnRunnable).start();

        for(int i=0;i<1000;i++){
            System.out.println(">>主线程输出了:"+i);
        }
    }
}

在这里插入图片描述

3. 实现callable接口

① 重写 call 方法
② 创建目标对象
③ 创建执行服务
④ 提交执行
⑤ 获取结果
⑥ 关闭服务

package com.example.myjava.javaMultithreading;

import java.util.concurrent.*;

/**
 * @Description:
 * @Author: Hanzao
 * @Date: 2022/01/14/20:24
 */
public class LearnCallable implements Callable<String> {
    @Override
    public String call() {
        for(int i=0;i<100;i++){
            System.out.println("子线程输出了"+i+Thread.currentThread().getName());
        }
        return "OK!";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        LearnCallable learnCallable1 = new LearnCallable();
        LearnCallable learnCallable2 = new LearnCallable();
        LearnCallable learnCallable3 = new LearnCallable();

        ExecutorService service = Executors.newFixedThreadPool(3);

        Future<String> r1 = service.submit(learnCallable1);
        Future<String> r2 = service.submit(learnCallable2);
        Future<String> r3 = service.submit(learnCallable3);

        String result1 = r1.get();
        String result2 = r2.get();
        String result3 = r3.get();

        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
        
		service.shutdown();
    }
}

这篇关于自学笔记-java多线程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!