Java의 여러 스레드간에 클래스 배열을 공유하려면 어떻게합니까? 나는 모두 입력 클래스의 배열을 공유하고 배열 (즉)의 요소를 인쇄하는 2 개 스레드를 원하는 이제Java의 여러 스레드간에 자원을 공유하려면 어떻게합니까?
public class Input {
int index;
int[] input = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
public Input(){
index = 0;
}
public void print(int index){
System.out.println(input[index]);
}
synchronized public int getIndex(){
if(index == 15)
return -1;
return index++;
}
}
:
내가 다음과 같이 배열을 가진 클래스라는 입력을 말해봐 스레드는 함께 15 배 (배열의 요소 수) 인쇄해야합니다. 마지막으로public class MyThread implements Runnable{
Thread t;
int index;
Input ip;
public MyThread(Input ip, String name){
t = new Thread(this, name);
this.ip = ip;
index = 0;
t.start();
}
@Override
public void run() {
while((index=ip.getIndex())!=-1){
System.out.println(t.getName());
ip.print(index);
}
}
}
그리고, 스레드 설정하는 코드 :
public class Caller {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Input ip = new Input();
MyThread t1 = new MyThread(ip, "Thread1");
MyThread t2 = new MyThread(ip, "Thread2");
t1.t.join();
t2.t.join();
}
}
출력은해야 뭔가 같은 :
Thread1
을이 내 스레드 클래스입니다 ,363,210
Thread2
2
Thread2
3
Thread1
4
Thread2
5
01,235,등이 배열의 마지막 요소에 도달 할 때까지 계속됩니다.
그리고 귀하의 질문은 무엇입니까? – Krumia
당신이 가지고있는 것은 괜찮을 것이지만 이것은 사소한 클래스이고 루프의 주요 부분에서 동기화 된 메서드를 사용하기 때문에 아마도 Thread1이 끝나기 전에 Thread1이 종료 될 것입니다. –
오오 그렇습니다. 더 큰 어레이에서 작동하는 것 같습니다. 미안합니다. 하지만 출력 결과는 다음과 같습니다. Thread1 Thread2 2 1 Thread1 3 (스레드 이름이 여러 번 인쇄됩니다). 또한, 어떻게 잠을 자지 않고 교대로 만들 수 있습니까? – drunkenfist