Skip to content

Instantly share code, notes, and snippets.

@SalithaUCSC
Last active March 25, 2020 01:41
Synchronization in Java
// RESOURCE GOING TO BE SHARED
class Resource {
private String name;
public synchronized void getAccess(String resource) {
System.out.println(resource+" is accessed by "+Thread.currentThread().getName());
try {
Thread.sleep(1000);
}
catch (Exception e) {
System.out.println("Thread Exception Found!");
}
System.out.println(resource+" is released by "+Thread.currentThread().getName());
}
public void setName(String name){
this.name = name;
}
public String getName() {
return name;
}
}
// THREAD
class ThreadRun extends Thread {
Resource resource;
ThreadRun(Resource obj){
resource = obj;
}
@Override
public void run(){
resource.setName("R");
// CALL THE RESOURCE ACCESS METHOD
resource.getAccess(resource.getName());
}
}
public class SyncExample {
public static void main(String args[]) {
final Resource obj = new Resource();
ThreadRun t1 = new ThreadRun(obj);
ThreadRun t2 = new ThreadRun(obj);
t1.start();
t2.start();
}
}
// OUTPUT
// R is accessed by Thread-0
// R is released by Thread-0
// R is accessed by Thread-1
// R is released by Thread-1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment