Thread not starts while other is too busy
I have multi thread application. I'm analyzing workflow of two threads. Thread_1
has cycle for(...)
. Thread_2
has some small job. In some cases Thread_2
not starts it's job while cycle for(...)
not finished in Thread_1
. Is it possible that system decides to put all resources for Thread_1
? How to give possibility to start Thread_2
while Thread_1
is in for(...)
. Should I put something like Thread.sleep(100)
there? Everything is in Java 1.4.
It will be great if you share some code piece, it's difficult to debug the code without looking logic. Ideally thread_1 and thread_2 should run independently. thread_2 can't wait to finish for loop in thread_1. Example:
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();
}
}
Output:
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.
you can make the first thread for loop pause for after a given number of iterations and set the static var th2_done to false to not waist Thread_1 time once the Thread_2 is done
Thread_1: for (...){ if(num_it % cycle && th2_done==false) sleep(100);}
Thread_2: for (...){} th2_done = true
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.