Advertisement
Guest User

Untitled

a guest
Dec 1st, 2015
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.99 KB | None | 0 0
  1. // Demonstrate thread groups.
  2. class NewThread extends Thread {
  3. boolean suspendFlag;
  4. NewThread(String threadname, ThreadGroup tgOb) {
  5. super(tgOb, threadname);
  6. System.out.println("New thread: " + this);
  7. suspendFlag = false;
  8. start(); // Start the thread
  9. }
  10. // This is the entry point for thread.
  11. public void run() {
  12. try {
  13. for(int i = 5; i > 0; i—) {
  14. System.out.println(getName() + ": " + i);
  15. Thread.sleep(1000);
  16. synchronized(this) {
  17. while(suspendFlag) {
  18. wait();
  19. }
  20. }
  21. }
  22. } catch (Exception e) {
  23. System.out.println("Exception in " + getName());
  24. }
  25. System.out.println(getName() + " exiting.");
  26. }
  27. void mysuspend() {
  28. suspendFlag = true;
  29. }
  30. synchronized void myresume() {
  31. suspendFlag = false;
  32. notify();
  33. }
  34. }
  35. class ThreadGroupDemo {
  36. public static void main(String args[]) {
  37. ThreadGroup groupA = new ThreadGroup("Group A");
  38. ThreadGroup groupB = new ThreadGroup("Group B");
  39. NewThread ob1 = new NewThread("One", groupA);
  40. NewThread ob2 = new NewThread("Two", groupA);
  41. NewThread ob3 = new NewThread("Three", groupB);
  42. NewThread ob4 = new NewThread("Four", groupB);
  43. System.out.println("\\nHere is output from list():");
  44. groupA.list();
  45. groupB.list();
  46. System.out.println();
  47. System.out.println("Suspending Group A");
  48. Thread tga[] = new Thread[groupA.activeCount()];
  49. groupA.enumerate(tga); // get threads in group
  50. for(int i = 0; i < tga.length; i++) {
  51. ((NewThread)tga[i]).mysuspend(); // suspend each thread
  52. }
  53. try {
  54. Thread.sleep(4000);
  55. } catch (InterruptedException e) {
  56. System.out.println("Main thread interrupted.");
  57. }
  58. System.out.println("Resuming Group A");
  59. for(int i = 0; i < tga.length; i++) {
  60. ((NewThread)tga[i]).myresume(); // resume threads in group}
  61. // wait for threads to finish
  62. try {
  63. System.out.println("Waiting for threads to finish.");
  64. ob1.join();
  65. ob2.join();
  66. ob3.join();
  67. ob4.join();
  68. } catch (Exception e) {
  69. System.out.println("Exception in Main thread");
  70. }
  71. System.out.println("Main thread exiting.");
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement