【Java多线程】线程状态及线程方法大全

➤ Java多线程编程【一文全解】

线程状态

在这里插入图片描述

线程有五大状态:

  • 创建状态 :new
  • 就绪状态 :start( )
  • 阻塞状态:sleep( ) wait( ) lock( ) synchronized( )
  • 运行状态:CPU调度执行
  • 死亡状态:线程终止
    在这里插入图片描述

线程方法

在这里插入图片描述

> 停止线程 stop( )

  • 不建议使用JDK提供的 stop( )、destroy( ) 【已废弃】;
  • 建议 让线程自己停下来
  • 即:使用一个标志位进行终止变量,当 flag=false ,则终止线程运行;
  1. 建议线程正常停止,利用次数,不建议死循环;
  2. 建议使用标志位 flag 判断;
  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) {
    
    
        //创建Runnable实现类对象,通过线程对象开启线程
        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(毫秒数)
  • sleep存在异常 InterruptedException;
  • sleep时间达到后,线程进入就绪状态;
  • sleep可以模拟网络延时,倒计时等;
  • 每个对象都有一个锁,sleep不会释放锁;

1 秒 = 1000 毫秒

倒计时 10、9、8 … 2、1 :

public class TestSleep implements Runnable {
    
    
    @Override
    public void run() {
    
    
        for (int i = 10; i > 0; i--) {
    
    
            System.out.println(i);
            try {
    
    
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
    
                throw new RuntimeException(e);
            }
        }
    }
    public static void main(String[] args) {
    
    
        TestSleep testSleep = new TestSleep();
        new Thread(testSleep).start();
    }
}

> 线程礼让 yield( )

  • 礼让线程,让当前正在执行的线程暂停,但不阻塞;
  • 将线程从 运行状态 为 就绪状态 ;
  • 让CPU重新调度,礼让不一定成功,看CPU心情;
//测试礼让线程
//礼让不一定成功,看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 合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞;
  • 可以理解为 “ 插队
//测试join方法  相当于“插队”
public class TestJoin implements Runnable{
    
    
    @Override
    public void run() {
    
    
        for (int i = 0; i < 1000; i++) {
    
    
            System.out.println("线程 BOSS 来啦"+i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
    
    
        //启动线程
        TestJoin testJoin = new TestJoin();
        Thread thread = new Thread(testJoin);
        thread.start();

        //主线程
        for (int i = 0; i < 500; i++) {
    
    
            if(i==200){
    
    
                thread.join();//线程插队
            }
            System.out.println("main "+i);
        }
    }
} //如果子线程会穿插在主线程中,可以在run()中加个sleep()
/*
	main 0
	main 1
	...
	main 198
	main 199
	线程 BOSS 来啦0
	线程 BOSS 来啦1
	线程 BOSS 来啦2
	...
	线程 BOSS 来啦998
	线程 BOSS 来啦999
	main 200
	main 201
	...
	main 498
	main 499
*/

> 线程状态观测 Thread.State

在这里插入图片描述

//观察线程状态
public class TestState {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        Thread thread = new Thread(()->{
    
      //Lambda表达式
            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();

        //观察启动后
        thread.start();
        state = thread.getState();
        System.out.println(state);//Run

        //只要线程不终止,就一直输出状态
        while(state!=Thread.State.TERMINATED){
    
    
            Thread.sleep(100);
            state = thread.getState();//更新线程状态
            System.out.println(state);//输出状态
        }
        thread.start();
    }
}
/* 输出:
    RUNNABLE
    TIMED_WAITING
    TIMED_WAITING
    ......
    TIMED_WAITING
    -------------
    TERMINATED
 */

> 线程的优先级 Priority

  • Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行;
  • 线程的优先级用数字表示,范围从 1 ~ 10 .
    • Thread.MIN_PRIORITY = 1 ;
    • Thread.MAX_PRIORITY = 10 ;
    • Thread.NORM_PRIORITY = 5 ;
  • 使用以下方法改变或获取优先级:
    • getPriority( )setPriority( int x)
//测试线程的优先级
public class TestPriority {
    
    
    public static void  main(String[] args ){
    
    
        //主线程默认优先级
        System.out.println(Thread.currentThread().getName()+"--->Priority  "+
            Thread.currentThread().getPriority());
        MyPriority myPriority = new MyPriority();

        Thread t1 = new Thread(myPriority);
        Thread t2 = new Thread(myPriority);
        Thread t3 = new Thread(myPriority);
        Thread t4 = new Thread(myPriority);
        //先设置优先级,再启动
        t1.start();

        t2.setPriority(1);
        t2.start();

        t3.setPriority(4);
        t3.start();

        t4.setPriority(Thread.MAX_PRIORITY);//MAX_PRIORITY=10
        t4.start();
    }
}
class MyPriority implements Runnable{
    
    
    @Override
    public void run() {
    
    
        System.out.println(Thread.currentThread().getName()+
                "--->Priority  "+Thread.currentThread().getPriority());
    }
}
/*
main--->Priority  5
Thread-0--->Priority  5
Thread-3--->Priority  10
Thread-2--->Priority  4
Thread-1--->Priority  1

进程已结束,退出代码0
 */

优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用,都是看CPU的调度


> 守护多线程 daemon

  • 线程分为 用户线程守护线程
  • 虚拟机必须确保用户线程执行完毕;
  • 虚拟机不用等待守护线程执行完毕;
  • 如:后台记录操作日志,监控内存,垃圾回收…等等;

守护线程是程序运行的时候在后台提供一种通用服务的线程。
所有用户线程停止,进程才会停掉所有守护线程,退出程序。

//测试守护线程
//上帝守护你
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 <--");
    }
}  //可以自己运行一下,很有意思

猜你喜欢

转载自blog.csdn.net/Lov1_BYS/article/details/128062361
今日推荐