a- /**
- * 两个线程轮流给数组添加随机数
- */
- public class T23 {
- private static int[] arr = new int[6];//共享的数据
- private static int index = 0;//数组下表指针
- private static boolean flag = false;
- public static void main(String[] args) throws InterruptedException {
- final Object lock = new Object();
- new Thread() {
- public void run() {
- synchronized (lock) {
- while (index < 6) {//index指示,数组是否已经添加结束
- while (flag) {
- try {
- lock.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- int num = (int) (Math.random() * 10 + 1);
- add1(num);
- flag = flag^true;//flag取反
- lock.notifyAll();
- }
- }
- };
- }.start();
- new Thread() {
- public void run() {
- synchronized (lock) {
- while (index < 6) {
- while (!flag) {
- try {
- lock.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- int num = (int) (Math.random() * 10 + 1);
- add1(num);
- flag = false;
- // flag = flag^true;
- lock.notifyAll();
- }
- }
- };
- }.start();
- while(index<6){
- Thread.sleep(1);
- }
- for(int i:arr)//遍历输出数组
- System.out.print(i+" ");
- }
- public static void add1(int i){
- if(index<6){
- arr[index] = i;//对共享数据进行操作需要进行同步
- System.out.println("arr["+index+"] = "+i
- +"..."+Thread.currentThread().getName());
- index++;
- }
- }
- }
复制代码- arr[0] = 3...Thread-0
- arr[1] = 2...Thread-1
- arr[2] = 7...Thread-0
- arr[3] = 7...Thread-1
- arr[4] = 6...Thread-0
- arr[5] = 9...Thread-1
- 3 2 7 7 6 9
复制代码
|
|