GamerBhai02

8. Shared resources

Jan 16th, 2025
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.92 KB | Source Code | 0 0
  1. class Resource{
  2.     public String name;
  3.     public Resource(String name){
  4.         this.name = name;
  5.     }
  6.     public String getName(){
  7.         return name;
  8.     }
  9. }
  10. class ThreadA extends Thread{
  11.     private Resource R1;
  12.     private Resource R2;
  13.     public ThreadA(Resource res1, Resource res2){
  14.         this.R1 = res1;
  15.         this.R2 = res2;
  16.     }
  17.     public void run(){
  18.         synchronized(R1){
  19.             System.out.println("ThreadA locked "+R1.getName());
  20.             try{
  21.                 Thread.sleep(100);
  22.             }catch(InterruptedException e){
  23.                 System.out.println(e);
  24.             }
  25.             synchronized(R2){
  26.                 System.out.println("ThreadA locked "+R2.getName());
  27.                 System.out.println("ThreadA is using resources.");
  28.             }
  29.         }
  30.     }
  31. }
  32. class ThreadB extends Thread{
  33.     private Resource R1;
  34.     private Resource R2;
  35.     public ThreadB(Resource res1, Resource res2){
  36.         this.R1 = res1;
  37.         this.R2 = res2;
  38.     }
  39.     public void run(){
  40.         synchronized(R2){
  41.             System.out.println("ThreadB locked "+R2.getName());
  42.             try{
  43.                 Thread.sleep(100);
  44.             }catch(InterruptedException e){
  45.                 System.out.println(e);
  46.             }
  47.             synchronized(R1){
  48.                 System.out.println("ThreadB locked "+R1.getName());
  49.                 System.out.println("ThreadB is using resources.");
  50.             }
  51.         }
  52.     }
  53. }
  54. public class Main{
  55.     public static void main(String[] args){
  56.     Resource res1 = new Resource("Resource A");
  57.     Resource res2 = new Resource("Resource B");
  58.     ThreadA t1 = new ThreadA(res1,res2);
  59.     ThreadB t2 = new ThreadB(res1,res2);
  60.     t1.start();
  61.     t2.start();
  62.     try{
  63.         t1.join();
  64.         t2.join();
  65.     }catch(InterruptedException e){
  66.         e.printStackTrace();
  67.     }
  68.     System.out.println("Main thread finished");
  69.     }
  70. }
Add Comment
Please, Sign In to add comment