java基础(多线程基础)

多线程

线程和进程

程序:程序是一段静态的代码,它是应用程序执行的蓝本

进程:进程是正在运行的程序,有自己的地址空间
1.并发:多个cpu同时执行多个任务
2.并行:一个cpu(采用时间片)同时执行多个任务

线程:
1.进程内部的一个执行单元,它是程序中一个单一的顺序控制流程
2.又被称为轻量级线程
3.如果在一个进程中执行了多个线程,用来执行不同的任务,则称为多线程

继承Thread类

龟兔赛跑多线程案例(内含步骤)

线程类:

package ThreadDemo;

//定义乌龟线程类步骤
//1.继承Thread类
public class TorThread extends Thread{

//  2.重写run方法
    @Override
    public void run(){
        while (true){
//            获取线程名:this.getName(),获取线程优先this.getPriority()
            System.out.println("乌龟领先了"+"   "+this.getName()+"  "+this.getPriority());
        }

    }
}

主类:

package ThreadDemo;

public class ThreadTest {
    public static void main(String[] args) {
//       创建一个乌龟对象
        TorThread tor = new TorThread();
//       启动乌龟线程
        tor.start();
//      启动兔子线程
//      获取线程名字Thread.currentThread().getName(),获取线程优先级Thread.currentThread().getPriority()
        while (true){
            System.out.println("兔子领先了"+"  "+Thread.currentThread().getName()+"  "+Thread.currentThread().getPriority());
        }
    }
}

实现Runnable接口

主类:

package RunnableDome;

public class RunnableTest1 {
    public static void main(String[] args) {
//        龟兔赛跑
        Runnable torrun = new TorRunnable();
//        创建一个Thread对象接收Runnable中实现的方法
        Thread thread1 = new Thread(torrun);
//        用Thread创建的对象启动线程
        thread1.start();
        while (true){
            System.out.println("兔子在跑"+"   "+Thread.currentThread().getName()+"   "+Thread.currentThread().getPriority());
        }
    }
    
}

继承Runnable接口事项run方法

package RunnableDome;
//继承Runnable接口实现其中的run方法
public class TorRunnable implements Runnable{
    @Override
    public void run() {
        while (true){
            System.out.println("乌龟在跑"+"   "+Thread.currentThread().getName()+"   "+Thread.currentThread().getPriority());
        }
    }
}

优点:便于多个线程共享统一资源

线程控制(Thread方法)

join():中途加入进程
sleep():让出cpu,进入阻塞状态。阻塞时间到,进入就绪状态,等待cpu
yield():让出cpu,进入就绪状态,等待cpu。让更高级别或者相同级别的线程得到更多的执行机会。
setDaemon():将指定的线程设置为后台线程。主线程执行结束,后台线程也结束。注意:只能在线程启动之前调用
inerrupt():修改线程的状态,需要线程本身检查状态的变化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牛仔不当马仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值