java - To make threads sleep in parallel, each with random amount of time -


i have set of threads, out of want "count" number of threads go sleep in parallel wake after random amount of time(stored in delay person). code thing in sequential order.

map<thread,person> threads=utils.getallthreads(); set<thread> th=threads.keyset(); int count =5; //no of threads go 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()+"  offline");      thread.sleep(((person)threads.get(t)).getdelayoffline());     //after sometime resume     count--;    t.resume();    system.out.println(((person)threads.get(t)).getname()+"  online");  }  catch(exception ex){  } 

so, want

  1. count number of threads go sleep in parallel , wake after random amount of time.

  2. is there way shuffle set? so, every time different threads go sleep.

**first of all, reconsider use of 'suspend' **, it's recipe trouble if threads hold locks.

if need 'suspend' anyway, might use java.util.timer , schedule task(s) wake threads.

    timer timer=new timer();      // each thread 't':     t.suspend();     final thread tfinal=t;      // shortcut allow timertask access 't' (alternatively can     // have explicit constructor timertask, , pass 't' it)     timer.schedule(             new timertask() {                 @override public void run() {                     tfinal.resume();                 }             },              your_random_value); 

obviously there variations, e.g. you have many threads repeatedly need suspended , resumed time, might have single timertask executes every, say, 30 seconds, , resumes threads eligible (assuming sleep time higher 30 secs - whole minutes - can live error margin of 30).


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -