[Java] 纯文本查看 复制代码
import java.util.ArrayList;
import java.util.Random;
public class LuckyBalls {
public static void main(String[] args) {
MyThread my=new MyThread();
Thread t1=new Thread(my,"前门");
Thread t2=new Thread(my,"后门");
t1.start();
t2.start();
}
}
public class MyThread implements Runnable{
private int person=100;
private Object obj=new Object();
private int front=0;
private int back=0;
public void run() {
while(true){
synchronized(obj){
//由于多次用到线程名称,特设置一个变量表示
String name=Thread.currentThread().getName();
if(person>0){
//Set集合更为简单,本例只是为了练习用contains()判断List集合是否含重复元素
ArrayList<String> list=new ArrayList<String>();
//注意用list.size()作为循环结束条件
for(int x=0;list.size()<7;x++){
Random r=new Random();
int num=r.nextInt(99)+1;
//转成字符串,对10以下数补零!
String s="";
if(num<10){
s="0"+String.valueOf(num);
}else{
s=String.valueOf(num);
}
//contains()方法是去重的关键
if(!list.contains(s)){
list.add(s);
}
}
//计数
if(name.equals("前门")){
front++;
}else{
back++;
}
//直接输出list集合即可满足所要求的格式,不必转成数组
System.out.println("编号为:"+(person--)+"的员工从"+name+"入场! 拿到的双色球彩票号码是:"+list);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
//输出前后门总数 并 跳出循环以结束线程运行
if(name.equals("前门")){
System.out.println(name+"共计"+front+"人");break;
}else{
System.out.println(name+"共计"+back+"人");break;
}
}
}
}
}
}