package heimaTest;
import java.util.Random;
import javax.swing.text.StyledEditorKit.ForegroundAction;
/*
* 2、声明一个共享数组,起两个线程,两个线程分别隔一段时间(可以写一个随机数),给数组中添加数据,每一个线程为数组添加3个数据即可。
*
* 思路:创建两个线程才采用单一的生产/消费机制
*
*/
//创建要操作的数组
class Array{
int[] arr = new int[6];
Random r = new Random();
int i= 0;
boolean flag = false;
public synchronized void set1() {
//判断对方是否执行
if(flag){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
arr[i]= r.nextInt(100);
//打印当前线程,获取线程名的方法不会写,以手工代替
System.out.println("线程1加入.... a["+i+"]= "+arr[i]);
i++;
flag = true;
notify();
}
public synchronized void set2(){
if(!flag){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
arr[i]= r.nextInt(100);
//打印当前线程
System.out.println("线程2加入.... a["+i+"]= "+arr[i]);
i++;
flag = false;
//唤醒对方
notify();
}
}
//创建线程1对象
class Thread1 implements Runnable{
Array a;
public Thread1(Array a) {
super();
this.a = a;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
a.set1();
//睡眠
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//创建线程2对象
class Thread2 implements Runnable{
Array a;
public Thread2(Array a) {
super();
this.a = a;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
a.set2();
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class Test02 {
public static void main(String[] args) {
//创建要操作的数组对象
Array a = new Array();
//创建两个线程对象
Thread1 thread1 = new Thread1(a);
Thread2 thread2 = new Thread2(a);
//创建两个线程
Thread t1 = new Thread(thread1);
Thread t2 = new Thread(thread2);
//开启线程
t1.start();
t2.start();
}
}
|