【问题标题】:Thread not starts while other is too busy线程未启动,而其他线程太忙
【发布时间】:2016-12-16 13:45:56
【问题描述】:

线程没有启动而其他线程太忙

我有多线程应用程序。我正在分析两个线程的工作流程。 Thread_1 有循环 for(...)Thread_2 有一些小工作。在某些情况下,Thread_2 不会启动它的工作,而循环for(...) 未在Thread_1 中完成。系统是否有可能决定将所有资源用于 Thread_1 ?当Thread_1for(...) 中时,如何提供启动Thread_2 的可能性。我应该把Thread.sleep(100) 之类的东西放在那里吗?一切都在 Java 1.4 中。

【问题讨论】:

  • 您的应用程序不应依赖于它不强制执行的任何执行顺序约束。是吗?
  • 您可以尝试使用Thread#yield(),但通常不建议在不需要时使用它。让两个线程并行运行真的很重要吗?如果是,他们在做什么以及他们之间正在发生什么同步/消息传递?您的描述也听起来像线程 1 可能是较低优先级的后台线程,而线程 2 应该具有更高的优先级,因此请尝试使用 Thead#setPriority()
  • 那是有线程的东西;你在那里没有太多的控制权。从这个意义上说:您似乎已经开始测量了。那么你为什么不更进一步,开始做实验,看看添加睡眠会如何改变事情。然后,java 1.4;严重地?您知道该版本甚至不再列在 Oracle 跟踪 java 版本的“生命结束”日期的表格中。
  • 我的应用程序不依赖于执行顺序,但我只是想知道为什么在某些情况下 Thread_2 没有启动而 Thread_1 没有完成它的工作。这意味着在某些情况下,当 Thread_1 有非连续作业时,Thread_2 将不会启动。我需要避免这种情况。线程是相互独立的。
  • 您是否使用线程转储来研究行为?也许这个问题是相关的:stackoverflow.com/questions/38354595/…

标签: java multithreading


【解决方案1】:

如果你分享一些代码片段会很棒,如果不看逻辑就很难调试代码。理想情况下,thread_1 和 thread_2 应该独立运行。 thread_2 等不及要完成 thread_1 中的循环。 示例:

class RunnableDemo implements Runnable {
   private Thread t;
   private String threadName;

   RunnableDemo( String name){
       threadName = name;
       System.out.println("Creating " +  threadName );
   }
   public void run() {
      System.out.println("Running " +  threadName );
      try {
         for(int i = 4; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);
            // Let the thread sleep for a while.
            Thread.sleep(50);
         }
     } catch (InterruptedException e) {
         System.out.println("Thread " +  threadName + " interrupted.");
     }
     System.out.println("Thread " +  threadName + " exiting.");
   }

   public void start ()
   {
      System.out.println("Starting " +  threadName );
      if (t == null)
      {
         t = new Thread (this, threadName);
         t.start ();
      }
   }

}

public class TestThread {
   public static void main(String args[]) {

      RunnableDemo R1 = new RunnableDemo( "Thread-1");
      R1.start();

      RunnableDemo R2 = new RunnableDemo( "Thread-2");
      R2.start();
   }   
}

输出:

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

【讨论】:

    【解决方案2】:

    您可以在给定次数的迭代后使第一个循环线程暂停,并将静态变量 th2_done 设置为 false,以便在 Thread_2 完成后不腰 Thread_1 时间

    线程_1: 为了 (...){ if(num_it % cycle && th2_done==false) sleep(100);}

    Thread_2: for (...){} th2_done = true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-03
      • 1970-01-01
      • 1970-01-01
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多