- //main
- public class ThreadTest {
- public static void main(String[] args) throws InterruptedException {
- //临界资源 共享数组
- int[] arr = new int[6];
- ArrIndex ai = new ArrIndex();
- Thread t1 = new Thread(new InputArr(arr, ai), "线程A");
- Thread t2 = new Thread(new InputArr(arr, ai), "线程B");
- t1.start();
- t2.start();
- t1.join();
- t2.join();
- }
- }
- public class ArrIndex extends Thread {
- //数组index
- public int index;
- }
- import java.util.Random;
- public class InputArr implements Runnable {
- private int[] arr;
- private int count;
- private ArrIndex ai;
- InputArr(int[] arr, ArrIndex ai) {
- this.arr = arr;
- this.ai = ai;
- }
- @Override
- public void run() {
- //每一个线程为数组添加3个数据即可
- while (count < 3) {
- //生成随机数
- int x = new Random().nextInt(5);
- synchronized (InputArr.class) {
- try {
- System.out.println(Thread.currentThread().getName() + "等待"
- + x + "秒");
- //两个线程分别隔一段时间
- Thread.sleep(x * 1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- //给数组添加数据
- arr[ai.index] = x;
- System.out.println(Thread.currentThread().getName() + "添加数据:"
- + arr[ai.index]);
- for (int i = 0; i < arr.length; i++) {
- System.out.println(arr[i]);
- }
- count++;
- ai.index++;
- }
- }
- }
- }
复制代码
把ArrIndex类改变为在main函数定义一个基本数据类型int ptr=0的变量传入线程 为什么不能实现角标的共享?求高人解答 谢谢 |
|