Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.ch53.hackerrank.general;
- import java.util.UUID;
- public class SharedResource {
- private volatile String resource = "default";
- public String getSharedResource() {
- return resource;
- }
- public void setSharedResource(String res) {
- this.resource = res;
- }
- public static void main(String[] args) {
- final SharedResource sr = new SharedResource();
- Thread t1 = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- while (true) {
- String currentValue = sr.getSharedResource();
- System.out.println("Thread 1 -> " + currentValue);
- sr.setSharedResource("Thread-1-" + UUID.randomUUID().toString());
- Thread.sleep(1000);
- }
- } catch (Exception e) {
- }
- }
- });
- Thread t2 = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- while (true) {
- String currentValue = sr.getSharedResource();
- System.out.println("Thread 2 -> " + currentValue);
- sr.setSharedResource("Thread-2-" + UUID.randomUUID().toString());
- Thread.sleep(1000);
- }
- } catch (Exception e) {
- }
- }
- });
- t1.start();
- t2.start();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement