Java 线程状态操作

Posted 今晚看星星

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 线程状态操作相关的知识,希望对你有一定的参考价值。

1. 线程停止

  • 在线程中如果出现死循环,有时需要让线程自己停止
  • Java JDK的stopdestory方法已经被遗弃
  • 因此设置一个标志位,让线程在一定条件下调用函数自己停下来
public class MainClass {

    public static void main(String[] args) throws InterruptedException {

        StopThread stopThread = new StopThread();

        new Thread(stopThread).start();

        Thread.sleep(3000);
        stopThread.stopThread();   // 运行三秒后停止

    }

}


class StopThread implements Runnable{

    private boolean flag = false;

    @Override
    public void run() {
        while(!flag) {
            System.out.println("The Thread is running!");
        }
    }
    public void stopThread(){
        this.flag = true;
    }

}

2. 线程休眠 sleep

  • 线程休眠可以用于程序的倒计时
  • 线程休眠可以模拟网络的延时
Thread.sleep([参数是整数,单位是毫秒]);

3. 线程礼让

  • 进行线程礼让的进程不阻塞,只是暂时让出CPU的使用权,相当于从运行态 -> 就绪态
  • 礼让的线程与就绪队列中的线程共同执行,执行次序未知
public class YieldTest {

    public static void main(String[] args) {
        YieldClass yc = new YieldClass();

        Thread t1 = new Thread(yc, "One");
        Thread t2 = new Thread(yc, "Two");

        t1.start();
        t2.start();

    }

}


class YieldClass implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "线程开始执行");
        Thread.yield();
        System.out.println(Thread.currentThread().getName() + "线程执行结束");
    }
}

4. 线程强制执行

  • Thread.join() 线程插队,直到线程运行结束
  • 线程执行结束之后,不能再次被运行
public class ThreadJoinTest {

    public static void main(String[] args) throws InterruptedException {

        // 在主线程中加入线程,强制执行
        ThreadJoin tj = new ThreadJoin();
        Thread t1 = new Thread(tj);

        for (int i = 0; i < 50; i++) {
            if (i == 20) {
                t1.start();
                t1.join();
            }
            System.out.println("Main Thread is running" + i);
        }

    }

}

class ThreadJoin implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "已经执行");
    }
}

5. 线程的优先级

  • Java提供一个线程调度器来监控程序启动后进入就绪状态的所有线程
  • 线程按照线程的优先级调度哪一个就绪的线程来执行
  • 线程的优先级越高,其被调度的可能性就越大,但并不能说明其一定被调度
  • 线程优先级的范围为 1-10, 不合法的数字将会抛出异常。Thread.MIN_PRIORITY = 1; Thread.MAX_PRIORITY = 10; Thread.NORM_PRIORITY = 5; 一般的进程优先级为5
public class ThreadPriority {

    public static void main(String[] args) {

        ThreadPri threadOne = new ThreadPri();
        Thread thread1 = new Thread(threadOne, "1");
        Thread thread2 = new Thread(threadOne, "2");

		// 设置线程的优先级
        thread2.setPriority(Thread.MAX_PRIORITY);
        
        thread1.start();
        thread2.start();

    }

}


class ThreadPri implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

6. 守护线程Daemon

  • 在Windows操作系统中成为服务,是运行在后台的进程,在Linux中,称为守护线程Daemon
  • 线程可分为用户线程和守护线程,JVM必须保证用户线程的执行而不需要等到守护线程执行完毕,守护线程随着用户线程执行的结束而结束,可能会再执行一小段时间
  • 守护线程的作用:后台日志、监控内存、垃圾回收
public class ThreadPriority {

    public static void main(String[] args) {

        ThreadPri threadOne = new ThreadPri();
        Thread thread1 = new Thread(threadOne, "1");
        thread1.setPriority(Thread.MAX_PRIORITY);

        Thread thread2 = new DaemonThread();

        // 先设置守护进程,然后开始
        thread2.setDaemon(true);
        thread2.start();

        thread1.start();


    }

}


class ThreadPri implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

class DaemonThread extends Thread{

    @Override
    public void run() {
        super.run();
        while(true) {
            System.out.println("Daemon is running");   // 守护进程只能执行一段时间,随着主进程的结束而结束
        }
    }
}

运行结果

Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
1
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running

Process finished with exit code 0

以上是关于Java 线程状态操作的主要内容,如果未能解决你的问题,请参考以下文章

newCacheThreadPool()newFixedThreadPool()newScheduledThreadPool()newSingleThreadExecutor()自定义线程池(代码片段

java多线程(线程通信-等待换新机制-代码优化)

Java 并发 -- 线程状态(Java线程六种状态操作系统层次的五种状态)线程池(七大核心参数)wait vs sleep

Java 并发 -- 线程状态(Java线程六种状态操作系统层次的五种状态)线程池(七大核心参数)wait vs sleep

java并发线程锁技术的使用

Java---JUC并发篇(多线程详细版)