Java 使线程并行休眠,每个线程都有随机的时间

Java 使线程并行休眠,每个线程都有随机的时间,java,multithreading,Java,Multithreading,我有一组线程,我想计算其中并行睡眠的线程数,但在随机延迟时间后醒来的线程数。此代码按顺序执行此操作 Map<Thread,Person> threads=utils.getAllThreads(); Set<Thread> th=threads.keySet(); int count =5; //no of threads that go to sleep System.out.println("count"+count); Iterator it=th.iterator

我有一组线程,我想计算其中并行睡眠的线程数,但在随机延迟时间后醒来的线程数。此代码按顺序执行此操作

Map<Thread,Person> threads=utils.getAllThreads();
Set<Thread> th=threads.keySet();
int count =5; //no of threads that go to sleep
System.out.println("count"+count);
Iterator it=th.iterator();
while(it.hasNext()){
    if(count==0) 
        break;

Thread t=(Thread) it.next();
try{
    t.suspend();
    System.out.println(((Person)threads.get(t)).getName()+"  is offline");

    Thread.sleep(((Person)threads.get(t)).getDelayOffline());

   //after sometime resume it

   count--;
   t.resume();
   System.out.println(((Person)threads.get(t)).getName()+"  back online");
 }

catch(Exception ex){

}
所以,我想要

计算并行睡眠和随机时间后醒来的线程数

有办法洗牌吗?所以,每次不同的线程进入睡眠状态


**首先,我会认真地重新考虑使用'suspend'**,这会带来麻烦,尤其是当线程持有锁时

如果仍然需要“挂起”,则可以使用java.util.Timer和调度任务来唤醒线程

    Timer timer=new Timer();

    // for each thread 't':
    t.suspend();
    final Thread tFinal=t;  
   // just a shortcut to allow my TimerTask to access 't' (alternatively you can 
   // have an explicit constructor for your TimerTask, and pass 't' to it)
    timer.schedule(
            new TimerTask() {
                @Override public void run() {
                    tFinal.resume();
                }
            }, 
            YOUR_RANDOM_VALUE);
显然有一些变化,例如,您有许多线程需要一直暂停和恢复,您也可能有一个TimerTask,每30秒执行一次,并恢复所有符合条件的线程,假设您的睡眠时间远高于30秒(比如整分钟),这样您就可以在30秒的误差范围内生存。

有一种洗牌方法,它支持用于扩展列表的集合,而不适用于Set。但是,如果您仍然想这样做,则可以使用以下代码:

Map<Thread,Person> threads=utils.getAllThreads();
Set<Thread> th=threads.keySet();
List<Thread> list = new ArrayList<Thread>(th);
Collections.shuffle(list);
th.clear();
th.addAll(list);

这将是昂贵的。另一种选择是根据集合的大小生成一些随机数,然后从集合中选择这些项。

集合是无序的,所以不能将其洗牌。GHashSet或已定义不能更改的顺序。GTreeSet、use List insteadBTW、Threadsuspend和Threadresume都不推荐使用。@SashaSalauyou我同意这两个都不推荐使用,但在我的代码使用中,在线程开始任何操作之前,我会让它们休眠以复制脱机用户的行为。因此,根据我的知识,暂停和恢复可能不会导致任何问题,如死锁等,因为它们根本不会启动。谢谢你的回复。嗨,这对我很有用。谢谢。我不知道计时器,这正是我想要做的。很高兴听到:我仍然可以问你是否真的需要“暂停”吗?我已经好几年没有在生产代码中看到它了。。。如果你知道自己在做什么,也不想被人唠叨,你当然可以忽略:事实上,我正在尝试复制一个离线用户的行为,用户最初是在线的,在随机时间后醒来,所以线程不包含任何监视器,因此挂起可能不会产生任何问题,我想。谢谢你的澄清:是的,事实上,我目前正在用随机数做这件事,但我一直在寻找一种更干净的方法