当其他人太忙时,线程不会启动
我有多线程应用程序。我正在分析两个线程的工作流程。 Thread_1
的周期为for(...)
。 Thread_2
有一些小工作。在某些情况下Thread_2
for(...)
未在Thread_1
中完成周期Thread_1
时,Thread_2
无法启动它。系统是否可能决定为Thread_1
放置所有资源?如何在for(...)
Thread.sleep(100)
期间启动-openmp
的可能性。我应该把omp_get_thread_num
放在那里吗?一切都在Java 1.4中。
答案 0 :(得分: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 :(得分:-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