Advertisement
Guest User

Untitled

a guest
Sep 25th, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. import java.util.concurrent.locks.Lock;
  2.  
  3. public class Worker implements Runnable {
  4.  
  5. String name = null;
  6. Lock lock = null;
  7.  
  8. public Worker(String name, Lock lock) {
  9. this.name = name;
  10. this.lock = lock;
  11. }
  12.  
  13. @Override
  14. public void run() {
  15. while (true) {
  16. lock.lock();
  17. try {
  18. Thread.sleep(1000);
  19. } catch (InterruptedException e) {
  20. // TODO Auto-generated catch block
  21. e.printStackTrace();
  22. }
  23. System.out.println(name);
  24. lock.unlock();
  25. }
  26. }
  27. }
  28.  
  29. import java.util.concurrent.locks.Lock;
  30. import java.util.concurrent.locks.ReentrantLock;
  31.  
  32. public class StartWorkers {
  33.  
  34. private void run(int n) {
  35. Lock lock = new ReentrantLock(true);
  36. Worker[] workers = new Worker[n];
  37. for (int i = 0; i < n; ++i) {
  38. workers[i] = new Worker(String.valueOf(i), lock);
  39. }
  40.  
  41. Thread[] threads = new Thread[n];
  42. for (int i = 0; i < n; ++i) {
  43. threads[i] = new Thread(workers[i]);
  44. threads[i].start();
  45. }
  46.  
  47. }
  48.  
  49. public static void main(String[] args) {
  50. StartWorkers startWorkers = new StartWorkers();
  51. startWorkers.run(5);
  52.  
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement