Guest User

Untitled

a guest
Sep 18th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. Wrapping a dead thread object in new thread object to restart it
  2. class Ex13 implements Runnable {
  3. int i = 0;
  4.  
  5. public void run() {
  6. System.out.println("Running " + ++i);
  7. }
  8.  
  9. public static void main(String[] args) throws Exception {
  10. Thread th1 = new Thread(new Ex13(), "th1");
  11. th1.start();
  12. //th1.join()
  13. Thread th2 = new Thread(th1);
  14. th2.start();
  15. }
  16. }
  17.  
  18. public void run() {
  19. if (target != null) {
  20. target.run();
  21. }
  22. }
  23.  
  24. public static class Ex13 implements Runnable {
  25. AtomicInteger i = new AtomicInteger(0);
  26. CountDownLatch latch;
  27. Ex13(CountDownLatch latch) {
  28. this.latch = latch;
  29. }
  30. public void run() {
  31. System.out.println("Running " + i.incrementAndGet());
  32. latch.countDown();
  33. }
  34. }
  35.  
  36. public static void main(String[] args) throws Exception {
  37. CountDownLatch latch = new CountDownLatch(2);
  38. Ex13 r = new Ex13(latch);
  39. Thread th1 = new Thread(r, "th1");
  40. th1.start();
  41. Thread th2 = new Thread(r);
  42. th2.start();
  43. latch.await(); // wait until both theads are executed
  44. System.out.println("Done");
  45. }
  46.  
  47. public class Ex13 implements Runnable {
  48. int i=0;
  49. public void run() {
  50.     System.out.println("Running "+ increment());
  51. }
  52. private synchronized int increment() {
  53. return ++i;
  54. }
  55. }
  56.  
  57. Thread t = Thread.currentThread();
  58. String name = t.getName();
  59. System.out.println("name=" + name);
Add Comment
Please, Sign In to add comment