Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ex2;
- import java.util.Random;
- import java.util.concurrent.Exchanger;
- public class MyThread extends Thread {
- private String label;
- private String word;
- private Exchanger<String> exchanger;
- public MyThread(String name, String word, Exchanger<String> exchanger) {
- this.label = name;
- this.word = word;
- this.exchanger = exchanger;
- }
- public String getLabel() {
- return label;
- }
- public void setLabel(String label) {
- this.label = label;
- }
- @Override
- public void run() {
- super.run();
- for(int i = 0; i < 3; i++) {
- System.out.println("Iteration: " + i + " " + this.getLabel() + " has " + this.word);
- System.out.println("Iteration: " + i + " " + this.getLabel() + " going to sleep.");
- Random r = new Random();
- try {
- Thread.sleep(r.nextInt(5000));
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("Iteration: " + i + " " + this.getLabel() + " ready to exchange");
- try {
- this.word = this.exchanger.exchange(this.word);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("Iteration: " + i + " " + this.getLabel() + " exchange completed");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement