package demo;
import java.util.Arrays;
/*
* 创建两条线程,轮流向数组中加入随机数,打印数组
*/
public class Test {
public int index = 0;// 在主类中设置索引并初始化以便其他类引用
public static void main(String[] args) throws InterruptedException {
int[] share = new int[6];// 设置想要存入入局的数组
Test gg = new Test();// 创建一个主函数对象以得到共享的索引
// 创建线程并启动
Thread t1 = new Thread(new WriteArr(share, gg), "1号线程");
Thread t2 = new Thread(new WriteArr(share, gg), "2号线程");
t1.start();
Thread.sleep(100);
t2.start();
// 线程执行完后才能让主函数遍历数组
try {
t1.join();
t2.join();
} catch (Exception e) {
e.printStackTrace();
}
// 打印数组
System.out.print(Arrays.toString(share));
}
}
class WriteArr implements Runnable {
private int[] share;
private Test gg;
// 初始化构造函数,获取数组与主类对象
public WriteArr(int[] share, Test gg){
this.share = share;
this.gg = gg;
}
public void run() {
// 每个线程存3个数据
for (int i = 0; i < 3; i++){
try {
Thread.sleep(1000);// 每次睡眠一段时间再存
} catch (Exception e) {
e.printStackTrace();
}
// 同步加锁防止索引错误
synchronized (share){
this.share[gg.index++] = (int) (Math.random() * 100);// 存入随机数
System.out.println(Thread.currentThread().getName() + "存入了"
+ share[gg.index - 1]);// 输出存入信息
}
}
}
}
|
|