/*
/**
*题目:声明一个共享数组,起两个线程,
两个线程分别隔一段时间(可以写一个随机数),给数组中添加数据,
每一个线程为数组添加3个数据即可。
*/
//方法一:
public class Demo21 {
public static void main(String[] args) {
int[] in = new int[6]; //需要控制因素
ArrayAdd aa = new ArrayAdd(in); //既然要共享资源,那么这里就只能创建一个线程执行地.
for(int x = 0; x < 2; x ++)
{
new Thread(aa).start(); //创建多个线程.
}
}
}
class ArrayAdd implements Runnable
{
private int[] in; //共享的资源,在创建时候,只能拥有一份.
private int num = 0;
ArrayAdd(int[] in)
{
this.in = in;
}
public void run()
{
while(num < in.length)
{
synchronized(in)
{
if(num < in.length)
{
try {
Thread.sleep(500); //线程只是等待一会时间,并没有释放锁.
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Random rd = new Random();
int i = rd.nextInt(20) + 1;
System.out.println(Thread.currentThread().getName() + "添加了:" + i);
in[num] = i;
num ++;
try {
in.wait(1000); //放弃cup,放弃锁.让其他线程拿锁.
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else
{
break;
}
}
}
}
}
//方法二:
class AddNum implements Runnable{
private static int[] a;
@Override
public void run() {
a=new int[6];
Random r = new Random();
for(int i=0;i<3;i++){
int j = r.nextInt(10)+1;
a[i] =j;
// System.out.print(a[i]+" ");
System.out.print(Thread.currentThread().getName()+" "+a[i]+" ");
}
}
}
public class Test21 {
public static void main(String[] args) {
AddNum add1 = new AddNum();
AddNum add2 = new AddNum();
Thread t1 = new Thread(add1);
Thread t2 = new Thread(add2);
t1.start();
t2.start();
}
} |
|