Java基础 线程2 线程的基本使用

线程的基本使用

案例1

线程应用案例1-继承Thread类

1、请编写程序,开启一个线程,该线程每隔1秒,在控制台输出“喵喵,我是小猫咪"

2、对上题进行改:当输出80次时,结束该线程

3、使用JConsole监控线程执行情况,并画出程序示意图

//查看cpu核心数/线程数

/**
 * @ClassName CpuNum
 * @Description
 * @Author 小黄debug
 * @Date 2022/3/20 13:01
 * @Version 1.0
 **/
public class CpuNum {
    public static void main(String[] args) {
        Runtime runtime = Runtime.getRuntime();
        //获取当前电脑的cpu数量/线程数
        int cpuNums = runtime.availableProcessors();
        System.out.println("当前有cpu个数="+cpuNums);

    }
}

//创建线程并使用

/**
 * @ClassName Thread01
 * @Description     通过继承Thread类创建线程
 * @Author 小黄debug
 * @Date 2022/3/20 13:06
 * @Version 1.0
 **/
public class Thread01 {
    public static void main(String[] args) throws InterruptedException{
        //创建一个Cat对象,当成线程使用
        Cat cat = new Cat();
        //启动线程,当start调用时,会调用run方法

        //源码分析
        /*
        //
        (1)
        public synchronized void start() {
            start0();
        }
        (2)
        //start0()是一个本地方法,是JVM调用,底层是c/c++实现的
        //真正实现多线程的效果,是start0(),而不是run
        private native void start0();
         */


        cat.start();    //启动线程 -> 最终会执行cat的run方法

        //cat.run();  //如果只执行run方法,run方法就是一个普通 的方法,没有启动子线程,就会把run方法执行完毕,才向下执行
        //说明:当main线程启动一个子线程,Thread-0,主线程不会阻塞,会继续执行
        //这时 主线程和子线程是交替执行。。
        for(int i = 0; i < 60; i++){
            System.out.println("主线程在执行中i="+i+"主线程名称="+Thread.currentThread().getName());
            //让主线程休眠
            Thread.sleep(1000);
        }


    }
}
//1、当一个类继承了Thread类,该类就可以当做线程使用
//2、我们会重写run方法,写上自己的业务代码
//3、run Thread类实现了Runnable接口的run方法
/*
@Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }
 */
class Cat extends Thread{

    int times = 0;
    //重写run方法
    public void run(){
        while(true) {
            //该线程每隔1秒,在控制台输出"喵喵,我是小猫咪"
            System.out.println("喵喵,我是小猫咪"+(++times)+"子线程名称="+Thread.currentThread().getName());
            //让该线程休眠1秒
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(times == 80){
                break;
            }
        }

    }
}

使用JConsole监控线程情况

当程序run起来后,在Termainal中输入jconsole后回车

进入到jconsole中,以不安全的方式连接,选择Thread-01(与类名相同)可以看到以下内容

案例2

说明:

1、Java是单继承的,在某些情况下一个类可能已经继承了某个父类,这时再用继承Thread类方法来创建线程显然不可能了

2、Java设计者们提供了另外一个方式创建线程,就是通过实现Runnable接口来创建线程

线程使用应用案例-实现Runnable

请编写程序,该程序 可以每隔1秒。在控制台输出"hi!",当输出10次后,自动退出,请使用Runnable接口的方式实现(这里底层使用了设计模式[代理模式-静态代理]=》代码模拟)

package com.hsydebug.threaduse;

/**
 * @ClassName Thread02
 * @Description 通过实现接口Runnable来开发线程
 * @Author 小黄debug
 * @Date 2022/3/20 14:19
 * @Version 1.0
 **/
public class Thread02 {
    public static void main(String[] args) {
//        Dog dog = new Dog();
//        //dog.start();这晨不能调用start;
//        //创建了Thread对象,把dog对象(实现Runnable),放入Thread
//        Thread thread = new Thread(dog);
//        thread.start();
        
        //==================================
        Tiger tiger = new Tiger();
        ThreadProxy threadProxy = new ThreadProxy(tiger);
        threadProxy.start();
    }
}
class Dog implements Runnable{
    int count = 0;
    public void run(){  //普通方法
        while(true){
            System.out.println("小狗汪汪叫:hi!="+(++count)+"="+Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(count == 10){
                break;
            }
        }
    }
}
//========================================
class Animal{}
class Tiger extends Animal implements Runnable{
    public void run(){
        System.out.println("老虎叫。。。。");
    }
}



//线程代理类,模拟一个极简的Thread类
class ThreadProxy implements Runnable{

    private Runnable target = null; //属性:类型是Runnable

    public ThreadProxy(Runnable target){
        this.target = target;
    }

    public void run(){
        if(target != null){
            target.run();
        }
    }

    public void start(){
        start0();//这个方法是真正实现多线程方法
    }
    public void start0(){
        run();
    }
}

案例3

线程使用应用案例-多线程执行

请编写一个程序 ,创建两个线程,一个线程每隔1秒输出 "hello,world",输出10次,退出,一个线程每隔1秒输出“hi",输出5次退出。Thread03.java

package com.hsydebug.threaduse;

/**
 * @ClassName Thread03
 * @Description
 * @Author 小黄debug
 * @Date 2022/3/20 16:09
 * @Version 1.0
 **/
public class Thread03 {
    public static void main(String[] args) {
//        A a = new A();
//        a.start();
//        B b = new B();
//        b.start();
        C c = new C();
        Thread threadC = new Thread(c);
        threadC.start();
        D d = new D();
        Thread threadD = new Thread(d);
        threadD.start();

    }
}

class A extends Thread{
    int count = 0;

    public void run(){
        while(true){
            System.out.println("线程A第"+(++count)+"次");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(count == 10){
                break;
            }
        }
    }
}
class B extends Thread{
    int count = 0;

    public void run(){
        while(true){
            System.out.println("线程B第"+(++count)+"次");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(count == 5){
                break;
            }
        }
    }
}

class ThreadSupper{}
class C extends ThreadSupper implements Runnable{

    int count = 0;

    public void run(){
        while(true){
            System.out.println("线程C第"+(++count)+"次");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(count == 10){
                break;
            }
        }
    }
}
class D extends ThreadSupper implements Runnable{

    int count = 0;

    public void run(){
        while(true){
            System.out.println("线程D第"+(++count)+"次");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(count == 5){
                break;
            }
        }
    }
}

1、从java的设计来看,通过继承Thread或者实现Runnable接口来创建线程本质上没有区别,从jdk帮助文档我们可以看到Thread类本身就实现了

2、实现Runnable接口方式更加适合多个线程共享一个资源的情况,并且避免了单继承的限制

3、售票系统,编程模拟三个售票窗口100,分别使用继承Thread和实现Runnable方式,并分析有什么问题,(超卖了),问题留在这里,后面解决

/**
 * @ClassName SellTicket
 * @Description 使用多线程模拟三个窗口同时售票100张
 * @Author 小黄debug
 * @Date 2022/3/20 16:58
 * @Version 1.0
 **/
public class SellTicket {
    public static void main(String[] args) {
//        SellTicket01 sellTicket01 = new SellTicket01();
//        SellTicket01 sellTicket02 = new SellTicket01();
//        SellTicket01 sellTicket03 = new SellTicket01();
//
//        //出现票数超卖
//        sellTicket01.start();
//        sellTicket02.start();
//        sellTicket03.start();

        //使用接口方式查看是否存在超卖
        SellTicker02 sellTicker02 = new SellTicker02();
        new Thread(sellTicker02).start();
        new Thread(sellTicker02).start();
        new Thread(sellTicker02).start();
    }
}

class SellTicket01 extends Thread{
    private static int ticketNum = 100;   //让多个线程共享ticketNum

    @Override
    public void run() {
        while(true){
            if(ticketNum <= 0){
                System.out.println("售票结束 。。");
                break;
            }
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("窗口"+Thread.currentThread().getName()
                    +"售出一张票,剩余票数"+(--ticketNum));
        }
    }
}

class SellTicker02 implements Runnable{
    //为什么这里不用静态,是因为SellTicker02只new了一次,所有的都ticketNum都指向这里
    private int ticketNum = 100;   //让多个线程共享ticketNum

    @Override
    public void run() {
        while(true){
            if(ticketNum <= 0){
                System.out.println("售票结束 。。");
                break;
            }
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("窗口"+Thread.currentThread().getName()
                    +"售出一张票,剩余票数"+(--ticketNum));
        }
    }
}

线程终止

基本说明

1、当线程完成任务后,会自动退出

2、还可以通过使用变量来控制run方法退出的方式停止线程,即通知方式

/**
 * @ClassName ThreadExit_
 * @Description
 * @Author 小黄debug
 * @Date 2022/3/20 17:41
 * @Version 1.0
 **/
public class ThreadExit_ {
    public static void main(String[] args) throws InterruptedException {
        T t1 = new T();
        t1.start();
        //如果希望main线程去控制t1线程中止,就必须可以修改loop变量
        //让t1退出run方法,从而终止t1线程 -->通知方式
        Thread.sleep(10000);
        System.out.println("通知t1线程中止");
        t1.setLoop(false);
    }
}

class T extends Thread{
    int count = 0;
    //设置一个控制变量
    private boolean loop = true;
    @Override
    public void run() {
        while(loop){
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("T运行中。。。。"+(++count));
        }
    }

    public void setLoop(boolean loop) {
        this.loop = loop;
    }
}

线程常用方法

1、setName        //设置线程名称,使之与参数name相同

2、getName        //返回该线程的名称

3、start                //使线程开始执行;Java虚拟机底层调用该线程的start()方法

4、run                //调用线程对象run方法

5、setPriority       //更改线程优先级

6、getPriority        //获取线程的优先级

7、sleep                //在指定的毫秒数内让当前正在执行的线程休眠(暂停执行)

8、interrupt                //中断线程

注意事项和细节

1、start底层会创建新的线程,调用run,run就是一个简单的方法调用,不会启动新线程

2、线程优先级的范围

3、interrupt中断线程,但并没有真正的线束线程,所以一般用于中断正在休眠的线程

4、sleep:线程的静态方法,使当前线程休眠

/**
 * @ClassName ThreadMethod01
 * @Description
 * @Author 小黄debug
 * @Date 2022/3/20 18:15
 * @Version 1.0
 **/
public class ThreadMethod01 {
    public static void main(String[] args) throws InterruptedException {
        //测试相关的方法
        T t = new T();
        t.setName("小黄");
        t.setPriority(Thread.MIN_PRIORITY);
        t.start();//启动子线程

        //主线程打印5hi,然后中断子线程的休眠
        for(int i = 0; i < 5; i++){
            Thread.sleep(1000);
            System.out.println("hi"+i);
        }
        System.out.println(t.getName()+"线程优先级="+t.getPriority());
        t.interrupt();
    }
}

class T extends Thread{
    @Override
    public void run() {
        while(true) {
            for (int i = 0; i < 100; i++) {
                //Thread.currentThread().getName() 获取当前线程的名称
                System.out.println(Thread.currentThread().getName() + "吃包子~~~" + i);
            }
            try {
                System.out.println(Thread.currentThread().getName() + "休眠中~~~");
                Thread.sleep(20 * 1000);
            } catch (InterruptedException e) {
                //当该线程执行到一个interrupt方法时,就会catch一个异常,可以加入自己的业务代码
                //InterruptedException是捕获到一个中断异常
                System.out.println(Thread.currentThread().getName() + "被interrupt了");
            }
        }
    }
}

线程常用方法

常用方法第二组

1、yield:线程和礼让,让出cpu,让其他线程执行,但礼让的时间不确定,所以也不一定礼让成功

2、join:线程的插队。插队的线程一旦插队成功,则肯定先执行完插入的线程所有的任务

案例:创建一个子线程,每隔1S输出hello,输出20次,主线程每隔1秒,输出hi,输出20次。要求:两个线程同时执行,当主线程输出5次后,就让子线程远行完毕,主线程再继续

/**
 * @ClassName ThreadMethod02
 * @Description
 * @Author 小黄debug
 * @Date 2022/3/20 18:41
 * @Version 1.0
 **/
public class ThreadMethod02 {
    public static void main(String[] args) throws InterruptedException {
        T2 t2 = new T2();
        t2.start();

        for(int i = 1; i<=20; i++){
            Thread.sleep(1000);
            System.out.println("主线程吃了"+i+"包子");
            if(i == 5){
                System.out.println("主线程礼让子线程");
                //join,线程插队
                //t2.join();//这里是相当于让t2线程先执行完毕
                t2.join();
                //Thread.yield();//礼让,不不定成功

                System.out.println("线程(老大)吃完了,主线程(小弟)接着吃。。");
            }
        }

    }
}
class T2 extends Thread{
    @Override
    public void run() {
        for(int i = 1; i <= 20; i++){
            try {
                Thread.sleep(1000);//休眠1秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("子线程吃了"+i+"包子");
        }
    }
}

线程常用方法

练习

ThreadMethodExercise.java

1、主线程每隔1s,输出hi,一共10次

2、当输出到hi 5时,启动一个子线程(要求实现Runnable),每隔1s输出hello,等该线程输出10次hello后,退出

3、主线程继续输出hi,直到主线程退出

4、如图,完成代码,其实线程插队

/**
 * @ClassName ThreadMethodExercise
 * @Description
 * @Author 小黄debug
 * @Date 2022/3/20 18:55
 * @Version 1.0
 **/
public class ThreadMethodExercise {
    public static void main(String[] args) throws InterruptedException {
        Thread t3 = new Thread(new T3());
        for (int i = 1; i <= 10; i++) {
            Thread.sleep(1000);
            System.out.println("主线程hello="+i);
            if(i == 5) {
                t3.start();
                t3.join();  //t3进行抢占
            }
        }
    }

}
class T3 implements Runnable{
    @Override
    public void run() {
        for(int i = 1; i <= 10; i++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("子线程hello="+i);
        }
    }
}
//运行结果
/*
主线程hello=0
主线程hello=1
主线程hello=2
主线程hello=3
主线程hello=4
主线程hello=5
子线程hello=1
子线程hello=2
子线程hello=3
子线程hello=4
子线程hello=5
子线程hello=6
子线程hello=7
子线程hello=8
子线程hello=9
子线程hello=10
主线程hello=6
主线程hello=7
主线程hello=8
主线程hello=9
 */

线程的常用方法

用户线程和守护线程

1、用户线程:也叫工作线程,当线程的任务执行完或通知方式结束 

2、守护线程:一般是为工作线程服务的,当所有的用户线程结束,守护线程自动结束

3、常见的守护线程:垃圾回收机制

应用案例ThreadMethod03.java

测试如何 将一个线程设置成守护线程

/**
 * @ClassName ThreadMethod03
 * @Description
 * @Author 小黄debug
 * @Date 2022/3/20 19:14
 * @Version 1.0
 **/
public class ThreadMethod03 {
    public static void main(String[] args) throws InterruptedException {
        MyDaemonThread myDaemonThread = new MyDaemonThread();
        //如果我们希望当main线程结束后,子线程自动结束
        //只需要将子线程设为守护线程即可
        myDaemonThread.setDaemon(true);
        myDaemonThread.start();
        
        for(int i = 1; i <= 10; i++){
            System.out.println("我爱学习我爱学习");
            Thread.sleep(1000);
        }
    }
}

class MyDaemonThread extends Thread{
    public void run(){
        for(;;){    //无限循环
            try {
                Thread.sleep(1000);   //休眠1000毫秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("不如跳舞");
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值