public class DoubleThread {
public static void main(String[] args) {
TwoThread tt = new TwoThread();
new Thread(tt, "1").start();
new Thread(tt, "2").start();
}
}
class TwoThread implements Runnable {
int[] arr = new int[6];
int x = 0;
Object obj = new Object();
public void run() {
while (true) {
synchronized (obj) {
if (x < arr.length) {
arr[x] = (int) (Math.random() * 10 + 1);
System.out.println("线程" + Thread.currentThread().getName() + "注入的第" + (x + 1) + "个数是" + arr[x]);
x++;
} else {
if (x == arr.length) {
System.out.println("数组输入完成");
method();
x++;
break;
} else {
break;
}
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void method() {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
if (i != arr.length - 1) {
System.out.print(arr[i] + ",");
} else {
System.out.println(arr[i] + "]");
}
}
}
}
上面是源代码
我希望用Runnable的实现类做到线程的有序输入
就是线程1加入到数组中一个随机数,然后线程2加入一个,然后再线程1.
在我这个代码的前提下有希望实现么?
求解,如果不能,请说明原因.
|
|