多线程,求帮忙该一下程序

成一粒 成一粒 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
/**
* 要求5个窗口同时开始售出100张票
* 并保存这一百张票中在那些窗口(及5个线程)中售出了那些票
* */
import java.util.Random;
import java.util.Vector;
import java.util.LinkedList;
public class test{
public static void main(String[] args){
Runnable r=new CreatThread(5,100);
Thread t1=new Thread(r,"thread1");
Thread t2=new Thread(r,"thread2");
Thread t3=new Thread(r,"thread3");
Thread t4=new Thread(r,"thread4");
Thread t5=new Thread(r,"thread5");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
class CreatThread implements Runnable{
private Object obj=1;
private int M;//存储总量
private int N;//窗口个数
private Vector<Integer> store;
private LinkedList<Integer> h1;
private LinkedList<Integer> h2;
private LinkedList<Integer> h3;
private LinkedList<Integer> h4;
private LinkedList<Integer> h5;

public CreatThread(int N,int M){
this.M=M;
this.N=N;
this.store=new Vector<Integer>();
this.store.setSize(N);//存储总量
for(int i=0;i<M;i++){
store.add(i);
}

this.h1=new LinkedList<Integer>();
this.h2=new LinkedList<Integer>();
this.h3=new LinkedList<Integer>();
this.h4=new LinkedList<Integer>();
this.h5=new LinkedList<Integer>();
}
public void run(){
synchronized(obj){
int i=0;
while(i<this.M){
Random ra=new Random();
int num=ra.nextInt(this.M);
if(store.contains(num)){
GetThreadArray(Thread.currentThread().getName()).add(num);
store.remove(store.indexOf(num));
}
}
}
}

public LinkedList<Integer> GetThreadArray(String name){
if(name.equals("thread1"))
return h1;
if(name.equals("thread2"))
return h2;
if(name.equals("thread3"))
return h3;
if(name.equals("thread4"))
return h4;
else
return h5;

}
}
...全文

相关推荐

评论 8
收藏 已收藏
分享
返回顶部
成一粒
Java SE 62,621 成员 307,251 内容