java多线程--3 线程状态、线程方法、线程类型

java多线程--3 线程状态、线程方法、线程类型

线程状态

  • 创建状态:

  • **就绪状态: **

    • 进入状态:
      1. 创建状态:启动线程
      2. 阻塞状态:阻塞解除
      3. 运行状态:释放CPU资源
  • 阻塞状态:

    • 进入状态:
      1. 运行状态:等待用户输入、线程休眠等
  • 运行状态:

    • 进入状态:

      1.就绪状态:获得CPU资源

  • 死亡状态:

    • 进入状态:

      1.运行状态:线程自然执行完毕、外部干涉终止线程。

线程方法

方法 说明
setPrioity(int newPriority) 更改线程的优先级
static void sleep(long millis) 在指定的毫秒数内让当前正在执行的线程休眠
void join() 等待线程终止
static void yield() 暂停当前正在执行的线程对象,并执行其他线程
void interrupt() 中断线程,别用这种方式
boolean isAlive() 测试线程是否处于活动状态

终止线程

  • 不推荐使用JDK提供的stop()、destroy() 。 已经废弃
  • 推荐线程自己停止下来,建议使用一个标志位进行终止线程,当flag = false,则终止线程运行。
package com.ssl.demo03;

//测试stop
//1.建议线程正常停止----->利用次数,不建议死循环
//2.建议使用标志位----->设置一个标志位
//3.不要使用stop或者destroy等过时或者JDK不建议使用的方法

public class TestStop implements Runnable{

    //1.设置一个标志位
    private boolean flag = true;

    @Override
    public void run() {
        int i = 0;
        while(flag){
            System.out.println("run.....Thread"+i++);
        }
    }

    //2.设置一个公开的方法停止线程,转换标志位
    public void stop(){
        this.flag = false;
    }
    public static void main(String[] args) {

        TestStop testStop = new TestStop();

        new Thread(testStop).start();

        for (int i = 0; i < 1000; i++) {
            System.out.println("main:"+i);
            if (i == 900){
                //调用stop方法,切换标志位,让线程终止
                testStop.stop();
                System.out.println("线程该停止了");
            }
        }

    }
}

线程休眠 sleep

  • sleep(时间) 指定当前线程阻塞的毫秒数;
  • sleep存在异常InterruptedException;
  • sleep时间达到后,线程进入就绪状态;
  • sleep可以模拟网络延时,倒计时等;
  • 每个对象都有一个锁,sleep不会释放锁。

模拟网络延时 存在不安全问题,后面解决

package com.ssl.demo03;

import com.ssl.demo01.TestThread5;

public class TestSleep implements Runnable{

    //票数
    private int ticketNums = 10;

    @Override
    public void run() {
        while (true) {
            if(ticketNums==0)
                break;
            //模拟延时,会存在并发问题
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //得到当前线程的名字
            System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"票");
        }
    }

    public static void main(String[] args) {
        TestThread5 tickle = new TestThread5();


        Thread thread1 = new Thread(tickle,"小明");
        Thread thread2 = new Thread(tickle,"大黄");
        Thread thread3 = new Thread(tickle,"老师");
        Thread thread4 = new Thread(tickle,"黄牛党");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }


}

模拟倒计时

  1. 倒计时10s
package com.ssl.demo03;

public class TestSleep2 {

    public static void main(String[] args){
        try {
            tenDown();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    public static void tenDown() throws InterruptedException {
        int num =10 ;
        while(true){
            Thread.sleep(1000);
            System.out.println(num--);
            if(num<=0){
                break;
            }
        }
    }
}
  1. 显示当前时间
package com.ssl.demo03;

import java.text.SimpleDateFormat;
import java.util.Date;

public class TestSleep3 {
    public static void main(String[] args) {
        //打印当前系统时间
        Date startTime = new Date(System.currentTimeMillis());//获取系统当前时间
        while(true){
            try {
                Thread.sleep(1000);
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
                startTime = new Date(System.currentTimeMillis());  //更新当前时间
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

线程礼让yield

  • 礼让线程,让当前正在执行的线程暂停,但不阻塞
  • 将线程从运行状态转为就绪状态
  • 让cpu重新调度,礼让不一定成功!看cpu心情
package com.ssl.demo03;

//测试礼让线程
//礼让不一定成功,看cpu心情
public class TestYield {

    public static void main(String[] args) {
        MyYield myYield = new MyYield();

        new Thread(myYield,"a").start();
        new Thread(myYield,"b").start();

    }

}

class MyYield implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"线程开始执行");
        Thread.yield();     //礼让
        System.out.println(Thread.currentThread().getName()+"线程停止执行");
    }
}

线程强制执行 join

  • join合并线程,待此线程执行完成后,在执行其他线程,其他线程阻塞。
  • 类似插队,少用,因为会阻塞其他线程
package com.ssl.demo03;

public class TestJoin implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("线程VIP来了"+i);
        }
    }

    public static void main(String[] args) {
        TestJoin testJoin = new TestJoin();

        Thread thread = new Thread(testJoin);
        thread.start();

        //主线程
        for (int i = 0; i < 500; i++) {
            if (i==200) {
                try {
                    thread.join();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
                System.out.println("mian"+i);
        }
    }
}

观察测试线程的状态 静态方法getState()

一个线程只能启动一次

package com.ssl.demo03;

//观察测试线程的状态
public class TestState {

    public static void main(String[] args) {
        Thread thread = new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("////////");
        });

        //观察状态
        Thread.State state = thread.getState();
        System.out.println(state);

        thread.start();
        state = thread.getState();
        System.out.println(state);

        while (state != Thread.State.TERMINATED){   //只要线程一直不终止,就一直输出状态
            try {
                Thread.sleep(100);   
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            state = thread.getState();
            System.out.println(state);
        }

    }
}

线程的优先级 priority

  • Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
  • 线程优先级用数字表示,范围从1-10,也看CPU心情,优先级高的只是有优势
Thread.MIN_PRIORITY = 1;
Thread.MAX_PRIORITY = 10;
Thread.NORM_PRIORITY = 5;
  • 方法
    • 改变优先级:setPriority(int xxx)
    • 获取优先级:getPriority()
package com.ssl.demo03;

//测试线程优先级
public class TestPriority {
    public static void main(String[] args) {
        //主线程默认优先级
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());

        MyPriority myPriority = new MyPriority();

        Thread t1 = new Thread(myPriority,"t1");
        Thread t2 = new Thread(myPriority,"t2");
        Thread t3 = new Thread(myPriority,"t3");
        Thread t4 = new Thread(myPriority,"t4");
        Thread t5 = new Thread(myPriority);
        Thread t6 = new Thread(myPriority);
        t2.setPriority(1);
        t3.setPriority(4);
        t4.setPriority(Thread.MAX_PRIORITY);

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        //报错
        /*   超出范围1-10
        t5.setPriority(-1);
        t5.start();
        t6.setPriority(11);
        t6.start();
        */
    }
}

class MyPriority implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
    }
}

守护线程 daemon

  • 线程分为用户线程和守护线程
  • 虚拟机必须确保用户线程执行完毕
  • 虚拟机不用等待守护线程执行完毕,如,后台操作日志、监控内存、垃圾回收....
package com.ssl.demo03;

//测试守护线程
public class TestDaemon {
    public static void main(String[] args) {
        God god = new God();
        You you = new You();
        Thread thread = new Thread(god);
        thread.setDaemon(true);  //默认是false表示用户线程
        thread.start();   //守护线程启动
        new Thread(you).start();
    }

}

//上帝
class God implements Runnable{

    @Override
    public void run() {
        while(true){
            System.out.println("上帝保佑着你");
        }
    }
}

//你
class You implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 36500; i++) {
            System.out.println("开心的活着");
        }
        System.out.println("======goodbye!world!");
    }
}
posted @ 2022-10-01 21:04  林每天都要努力  阅读(42)  评论(0)    收藏  举报