- package com.itheima;
- /**
- * 2、声明一个共享数组,起两个线程,两个线程分别隔一段时间(可以写一个随机数),
- 给数组中添加数据,每一个线程为数组添加3个数据即可。
- */
- public class Test2 {
- public static void main(String[] args) throws Exception {
- // TODO Auto-generated method stub
- int arys[] = new int[6];
- thread1 T1 = new thread1(arys);
- thread2 T2 = new thread2(arys);
- Thread t1 = new Thread(T1);
- Thread t2 = new Thread(T2);
- t1.start();
- t2.start();
- for (int i = 0; i < arys.length; i++) {
- System.out.println(arys[i]);
- }
- }
- }
- class thread1 implements Runnable{
- private int arys[] = new int[6];
- public thread1(int[] arys) {
- // TODO Auto-generated constructor stub
- this.arys = arys;
- }
- @Override
- public void run() {
- // TODO Auto-generated method stub
- synchronized (arys) {
- for(int i = 0 ;i < 3 ; i++){
- arys[i] = i;
- System.out.println("thread1 " +"arys :" + arys[i]);
- }
- }
- }
-
- }
- class thread2 implements Runnable{
- private int arys[] = new int[6];
- public thread2(int[] arys) {
- // TODO Auto-generated constructor stub
- this.arys = arys;
- }
- @Override
- public void run() {
- // TODO Auto-generated method stub
- synchronized (arys) {
- for(int i = 3 ;i < 6 ; i++){
- arys[i] = i;
- System.out.println("thread2 " +"arys :" + arys[i]);
- }
- }
- }
-
- }
复制代码 |