일부 코드 조각을 공유하면 멋지 겠지만 논리를 찾지 않고 코드를 디버그하는 것은 어렵습니다. 이상적으로 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.
귀하의 응용 프로그램이 실행하지 않는 실행 순서 제약에 의존해서는 안된다. 그거야? –
'Thread # yield()'를 사용해 볼 수도 있지만 일반적으로 필요하지 않을 때는 사용하지 않는 것이 좋습니다. 두 스레드를 병렬로 실행하는 것이 정말로 중요합니까? 그리고 그렇다면 그들이 무엇을하고 있으며 그들 사이에 어떤 동기화/메시징이 일어나고 있습니까? 스레드 1은 우선 순위가 낮은 백그라운드 스레드 일 수 있지만 스레드 2는 우선 순위가 높아야하므로 'Thead # setPriority()'를 사용해보십시오. – Thomas
그건 쓰레드가있는 것입니다; 당신은 거기에서 많은 통제력을 가지고 있지 않습니다. 그런 의미에서 : 이미 ** 측정 ** 시작한 것 같습니다. 그러니 한발 더 나아가서 수면을 추가하는 것이 어떻게 바뀌는지를 실험 해보십시오. 그런 다음 java 1.4; 진지하게? 오라클이 Java 버전의 "end of life"날짜를 추적하는 테이블에이 버전이 더 이상 나열되지 않는다는 것을 알고 있습니다. – GhostCat