首页 文章

线程无法启动而其他线程太忙

提问于
浏览
0

线程无法启动而其他线程太忙

我有多线程应用程序 . 我正在分析两个线程的工作流程 . Thread_1 有周期 for(...) . Thread_2 有一些小工作 . 在某些情况下 Thread_2 没有启动它的工作,而循环 for(...) 没有在 Thread_1 中完成 . 是否有可能系统决定为 Thread_1 放置所有资源?如何在 Thread_1 处于 for(...) 时启动 Thread_2 的可能性 . 我应该把像_710392这样的东西放在那里吗?一切都在Java 1.4中 .

2 回答

  • -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.
    
  • 1

    你可以在给定次数的迭代之后使第一个线程用于循环暂停,并在Thread_2完成后将静态var th2_done设置为false而不是腰线Thread_1时间

    Thread_1:for(...){if(num_it%cycle && th2_done == false)sleep(100);} Thread_2:for(...){} th2_done = true

相关问题