Advertisement
Guest User

Untitled

a guest
Feb 21st, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.17 KB | None | 0 0
  1. package com.ch53.hackerrank.general;
  2.  
  3. import java.util.UUID;
  4.  
  5. public class SharedResource {
  6.  
  7.     private volatile String resource = "default";
  8.  
  9.     public String getSharedResource() {
  10.         return resource;
  11.     }
  12.  
  13.     public void setSharedResource(String res) {
  14.         this.resource = res;
  15.     }
  16.  
  17.     public static void main(String[] args) {
  18.         final SharedResource sr = new SharedResource();
  19.         Thread t1 = new Thread(new Runnable() {
  20.  
  21.             @Override
  22.             public void run() {
  23.                 try {
  24.                     while (true) {
  25.                         String currentValue = sr.getSharedResource();
  26.                         System.out.println("Thread 1 -> " + currentValue);
  27.                         sr.setSharedResource("Thread-1-" + UUID.randomUUID().toString());
  28.                         Thread.sleep(1000);
  29.                     }
  30.                 } catch (Exception e) {
  31.  
  32.                 }
  33.             }
  34.         });
  35.  
  36.         Thread t2 = new Thread(new Runnable() {
  37.  
  38.             @Override
  39.             public void run() {
  40.                 try {
  41.                     while (true) {
  42.                         String currentValue = sr.getSharedResource();
  43.                         System.out.println("Thread 2 -> " + currentValue);
  44.                         sr.setSharedResource("Thread-2-" + UUID.randomUUID().toString());
  45.                         Thread.sleep(1000);
  46.                     }
  47.                 } catch (Exception e) {
  48.  
  49.                 }
  50.             }
  51.         });
  52.         t1.start();
  53.         t2.start();
  54.     }
  55.  
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement