线程通讯问题
创建两个线程 分别依次给数组里面随机存放int数据
要求两个线程轮流存放各存放3次。
自己做了半天做成这样,也不知道还思路对不对。
求解答
import java.awt.Robot;
import java.util.Random;
public class Demo4{
final static shareArray1 sh = new shareArray1();
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i<3 ; i++){
try {
sh.Thread1(new Random().nextInt());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i<3;i++){
try {
sh.Thread1(new Random().nextInt());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
}
class shareArray1{
private static int[] sum = new int[6];
private static int n=0;
private static boolean badge = true;
public synchronized void Thread1(int i) throws InterruptedException{
while(!badge)
this.wait();
sum[n] = i;
System.out.print(Thread.currentThread().getName());
System.out.println(sum[n]);
n++;
Thread.sleep(3000);
badge = false;
this.notifyAll();
}
public synchronized void Thread2(int i) throws InterruptedException{
while(badge)
this.wait();
sum[n] = i;
System.out.print(Thread.currentThread().getName());
System.out.println(sum[n]);
n++;
Thread.sleep(3000);
badge = true;
this.notifyAll();
}
}
|
|