에서 두 개의 스레드 1-20 :인쇄 번호 나는 두 개의 스레드와 숫자 1-20를 인쇄하기 위해 노력하고있어 자바
- 에도 실 - 인쇄 짝수 번호.
- 이상한 스레드 - 홀수 만 인쇄하십시오.
또한 동기화를위한 잠금 개체가 있습니다.
내 응용 프로그램이 작동하지 않습니다. 문제가 무엇인지 말해 줄 수 있습니까?
내 코드 :
public class runIt
{
public static void main(String[] args)
{
Odd odd = new Odd("odd thread");
Even even = new Even("even thread");
odd._t.start();
even._t.start();
try{
odd._t.join();
even._t.join();
}
catch (InterruptedException e){
System.out.println(e.getMessage());
}
}
}
public class Constants{
static Object lock = new Object();
}
public class Even implements Runnable{
Thread _t;
String _threadName;
public Even(String threadName){
_threadName = threadName;
_t = new Thread(this);
}
@Override
public void run(){
for (int i = 0; i < 20; i++){
if (i % 2 == 0){
synchronized (Constants.lock){
try{
Constants.lock.wait();
Constants.lock.notifyAll();
}
catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(_threadName + " " + i + " ");
}
}
}
}
}
public class Odd implements Runnable{
Thread _t;
String _threadName;
public Odd(String threadName){
_threadName = threadName;
_t = new Thread(this);
}
@Override
public void run(){
for (int i = 0; i < 20; i++){
if (i % 2 == 1){
synchronized (Constants.lock){
try{
Constants.lock.wait();
Constants.lock.notifyAll();
}
catch (InterruptedException e1){
e1.printStackTrace();
}
System.out.println(_threadName + " " + i + " ");
}
}
}
}
}
내 출력은 다음과 같아야합니다
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
도와 주셔서 감사합니다. Tam.
은 여기를보세요 : http://stackoverflow.com/questions/6017281/odd-even-number-printing-using-thread 정확하게 필요한 것 같습니다. –
그래서 나는 이것이 새로운 학기가 막 시작된 곳을 의미한다고 생각하십니까? * 한숨 * – Voo
즉각적인 문제는 두 스레드가 잠금 대기 상태가되어 알림이 수신되지 않는다는 것입니다.이 코드에는 몇 가지 다른 문제가 있습니다. –