哎 做出来了
- package test;
- import java.util.Arrays;
- import java.util.Random;
- /*
- * 声明一个共享数组,起两个线程,两个线程分别隔一段时间(可以写一个随机数),
- * 给数组中添加数据,每一个线程为数组添加3个数据即可。
- * */
- class Resource
- {
- private int[] arr = new int[6];
- private int pos = 0;
- public synchronized void write(int num)
- {
- this.notify();
- arr[pos] = num;
- pos++;
- System.out.println(Thread.currentThread().getName()+":"+Arrays.toString(arr));
- try{this.wait();}catch(Exception e){}
- }
- }
- class Write2Array implements Runnable
- {
- private Resource r;
- Write2Array(Resource r) {
- // TODO Auto-generated constructor stub
- this.r = r;
- }
- public void run()
- {
- for(int x=0; x<3; x++)
- {
- try {
- Random random = new Random();
- try{Thread.sleep(random.nextInt(100));}catch(Exception e){}
- r.write(random.nextInt(100));
- } catch (Exception e) {
- // TODO: handle exception
- }
-
- }
- }
- }
- public class exam02 {
- public static void main(String[] args) {
- Resource r = new Resource();
- new Thread(new Write2Array(r)).start();
- new Thread(new Write2Array(r)).start();
- }
- }
复制代码
应该符合题意吧 |