package HomeWork;
import java.util.ArrayList;
import java.util.Random;
public class HomeWork1 {
/*有一个抽奖池,该抽奖池中存放了奖励的金额,该抽奖池用一个数组int[] arr = {10,5,20,50,100,200,500,800,2,80,300};
创建两个抽奖箱(线程)设置线程名称分别为“抽奖箱1”,“抽奖箱2”,随机从arr数组中获取奖项元素并打印在控制台上,格式如下:
抽奖箱1 又产生了一个 10 元大奖
抽奖箱2 又产生了一个 100 元大奖 */
public static void main(String[] args) {
//创建实现Runnable接口的实现类对象
ChouJiang2 cj = new ChouJiang2();
//创建两个线程并开启
new Thread(cj,"抽奖箱1").start();
new Thread(cj,"抽奖箱2").start();
}
}
class ChouJiang2 implements Runnable {
private int[] arr = {10,5,20,50,100,200,500,800,2,80,300};
private int num = arr.length;
private ArrayList<Integer> list = new ArrayList<Integer>();
//标志作用就是轮流执行
private boolean flag = true;
@Override
public void run() {
String threadName = Thread.currentThread().getName();
while(true) {
synchronized(this){
this.notifyAll();
if(num<=0)
break;
//创建随机数对象
Random r = new Random();
int index ;
//为了获取不重复的索引值
while(true) {
index = r.nextInt(arr.length);
if(list.contains(index))
continue;
else {
list.add(index);
break;
}
}
int money = arr[index];
if(flag) {
System.out.println(threadName + " 又产生了一个 "+money+" 元大奖");
num--;
flag = false;
// this.notifyAll();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println(threadName + " 又产生了一个 "+money+" 元大奖");
num--;
flag = true;
// this.notifyAll();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
// 同时开启两个线程,共同输出1-100之间的所有数字,并且将输出奇数的线程名称打印出来
class Test03 {
public static void main(String[] args) {
PrintNumber pn = new PrintNumber();
new Thread(pn,"线程a").start();
new Thread(pn,"线程b").start();
}
}
class PrintNumber implements Runnable {
private int num = 1;
@Override
public void run() {
while(true) {
synchronized (this) {
if(num>100)
break;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(num%2!=0) {
System.out.println(Thread.currentThread().getName()+"输出了: " + num);
}
num++;
}
}
}
}
/*public static void main(String[] args) {
}
}
class ChouJiang implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
try {
Thread.sleep(30);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "又产生了一个" );
}
}
}*/
|
|