Java基础之多线程

本文深入探讨Java多线程,包括线程同步、Lock锁、生产者消费者模式、阻塞队列、线程池、Volatile关键字以及Atomic包等核心概念。详细介绍了各种线程同步机制和并发工具类的使用,帮助理解Java并发编程的关键知识点。
摘要由CSDN通过智能技术生成

多线程

实现多线程方式一: 继承Thread类

public class MyThread extends Thread {
   
    @Override
    public void run() {
   
        for (int i = 0; i <= 100; i++) {
   
            System.out.println(i);
        }
    }
}
//=============================================
public class Test1 {
   
    public static void main(String[] args) {
   
        MyThread mt1 = new MyThread();
        MyThread mt2 = new MyThread();
        mt1.start();
        mt2.start();
    }
}

注意
1、为什么要重写run()方法
因为run()是用来封装杯线程执行的代码

2、run方法和start()方法的区别
run():封装线程执行的代码,直接调用,相当于普通方法调用
start():启动线程;由JVM调用此线程的run()方法

实现多线程方式二:  实现Runnable接口

public class MyRunnable implements Runnable{
   
    @Override
    public void run() {
   
        for (int i = 0; i < 100; i++) {
   
            System.out.println(i);
        }
    }
}

//=================================

public class Test1 {
   
    public static void main(String[] args) {
   
        MyRunnable myRunnable = new MyRunnable();
        Thread t1 = new Thread(myRunnable);
        Thread t2 = new Thread(myRunnable);
        t1.start();
        t2.start();
    }
}

实现多线程方式二:  实现Callable接口

public class MyCallable implements Callable<String> {
   
    @Override
    public String call() throws Exception {
   
        for (int i = 0; i <= 10; i++) {
   
            System.out.println(i);
        }
        return "好的";
    }
}

public class Test1 {
   
    public static void main(String[] args) throws 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值