繁体   English   中英

当其他人太忙时线程无法启动

[英]Thread not starts while other is too busy

当其他人太忙时线程无法启动

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

如果您共享一些代码片段,那就太好了,如果不看逻辑就很难调试代码。 理想情况下,线程_1和线程_2应该独立运行。 线程_2等不及要完成线程_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.

您可以在给定的迭代次数后使第一个用于循环的线程暂停,并在Thread_2完成后将静态var th2_done设置为false以使Thread_1不再紧缩

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

线程_2:for(...){} th2_done = true

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM