Advertisement
MarlonKuqi

SPP_TP34_exo2

Mar 11th, 2019
383
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.20 KB | None | 0 0
  1. package ex2;
  2.  
  3. import java.util.Random;
  4. import java.util.concurrent.Exchanger;
  5.  
  6.  
  7. public class MyThread extends Thread {
  8.     private String label;
  9.     private String word;
  10.     private Exchanger<String> exchanger;
  11.    
  12.     public MyThread(String name, String word, Exchanger<String> exchanger) {
  13.         this.label = name;
  14.         this.word = word;
  15.         this.exchanger = exchanger;
  16.     }
  17.  
  18.     public String getLabel() {
  19.         return label;
  20.     }
  21.  
  22.     public void setLabel(String label) {
  23.         this.label = label;
  24.     }
  25.  
  26.     @Override
  27.     public void run() {
  28.         super.run();
  29.         for(int i = 0; i < 3; i++) {
  30.             System.out.println("Iteration: " + i + " " + this.getLabel() + " has " + this.word);
  31.             System.out.println("Iteration: " + i + " " + this.getLabel() + " going to sleep.");
  32.             Random r = new Random();
  33.             try {
  34.                 Thread.sleep(r.nextInt(5000));
  35.             } catch (InterruptedException e) {
  36.                 e.printStackTrace();
  37.             }
  38.             System.out.println("Iteration: " + i + " " + this.getLabel() + " ready to exchange");
  39.             try {
  40.                 this.word = this.exchanger.exchange(this.word);
  41.             } catch (InterruptedException e) {
  42.                 e.printStackTrace();
  43.             }
  44.             System.out.println("Iteration: " + i + " " + this.getLabel() + " exchange completed");
  45.         }
  46.     }
  47.    
  48.    
  49.    
  50.  
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement