package com.heima.lei;
import java.util.Random;
public class Test01 {
/**implements Runnable synchronized
* 2个线程向同一数组中加随机数,每个数组加3个数,交替
* @param args
*/
public static void main(String[] args) {
ThreadArray ta = new ThreadArray();
Thread t1 = new Thread(ta);
Thread t2 = new Thread(ta);
t1.setName("第一个线程");
t2.setName("第二个线程");
t1.start();
t2.start();
}
}
class ThreadArray implements Runnable{
private static int []arr = new int [6];
int j=0;
//int sum = 0;
@Override
public void run() {
for(int i = 0;i < 3;i ++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
AddArray();
}
}
public synchronized void AddArray() {
Random r = new Random();
int num = r.nextInt(100);
arr[j] = num;
System.out.println(Thread.currentThread().getName()+"arr["+j+"]="+num);
j++;
}
}
2个线程向同一数组中加随机数,每个数组加3个数,交替
最新推荐文章于 2021-06-17 16:46:03 发布