有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中,在运行时为另一个线程抢占一个线程

如何通过停止JAVA中的当前处理线程来启动和运行新的、最重要的线程。i、 当前线程的处理正在进行,我们希望停止或暂停该线程一段时间,并执行一个新线程


共 (2) 个答案

  1. # 1 楼答案

    Java中没有对线程的细粒度控制。您通常会尝试避开线程优先级,因为它会生成脆弱的系统。但是,如果您必须这样做,您可以更改线程优先级,大多数系统都会考虑它

    Thread.currentThread().setPriority(Thread.MAX_PRIORITY-1); // make it important
    

    只有当其他线程确实支持此功能时,才能暂停它们。但请记住,暂停的线程仍然会占用所有内存和资源。暂停和恢复一个线程所需的工作可能不会以收益为理由。(在这方面,优先事项更好)

    例如,要暂停线程,可以使用工作线程中获得的锁。无论何时(被更重要的线程)锁定,它都会使工作线程暂停(没有CPU使用)

    class WorkerThread {
      Semaphore sem;
    
      void checkForPause() throws InterruptedExec{
        synchronized(sem) { // make sure unpauseThread() cant release it
          sem.aquire(); // will block when pauseThread aquired one
          sem.release();
        }
      }
    
      void pauseThread() {
        sem.aquire();
      }
    
      void unpauseThread() {
        synchronized(sem) { sem.release(); } // only release after checkForPause()
      }
    
      work run() {
        while(true) { // do something in a loop
          checkForPause();
          // do actual work in small steps
        }
      }
    }
    

    现在可以使用pauseThread()和unpauseThread()控制WorkerThread实例

    顺便说一句:在旧的Java中有Thread#suspend()Thread#resume(),但不应该在现代程序中使用。在deprecation notice中有一些替代代码

  2. # 2 楼答案

    您需要使用线程的类join()方法

    假设有两个线程T1和T2。 当您调用T1.start()T1.join()并调用T2.start()时,T1将等待T2完成它的工作,然后T1将执行

    请通过以下链接了解更多详细信息

    Thread join() method