Advertisement
georgeB96

Java Thread Synchronised with message

Nov 5th, 2021
755
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.27 KB | None | 0 0
  1.  
  2. public class Lab2 {
  3.    
  4.     public static void main(String[] args) {
  5.         Runnable joes = new SharingAResource("Eat at Joe's", 10, 2);
  6.         Runnable bills = new SharingAResource("Eat at Bill's", 10, 4);
  7.         Thread j = new Thread(joes);
  8.         Thread b = new Thread(bills);
  9.        
  10.         j.start();
  11.         b.start();
  12.         System.out.println("Billboard started");
  13.  
  14.         try {
  15.            
  16.             j.join();
  17.             b.join();
  18.         } catch (InterruptedException e) {
  19.             return;
  20.         }
  21.        
  22.         System.out.println("Billboard closed");
  23.  
  24.        
  25.        
  26.     }
  27.    
  28.    
  29.    
  30. }
  31.  
  32.  
  33. class SharingAResource implements Runnable {
  34.    
  35.     private String message;
  36.     private int counter;
  37.     private int pause;
  38.     private static Object screen = new Object();
  39.  
  40.     //constructor
  41.    
  42.     public SharingAResource(String message, int counter, int pause){
  43.         this.message = message;
  44.         this.counter = counter;
  45.         this.pause = pause * 1000;
  46.     }
  47.    
  48.     public void run() {
  49.         synchronized(screen) {
  50.             System.out.println("Entered the sync block, no other thread can use this resource");
  51.             for(int i=0; i<counter; i++) {
  52.                 try {
  53.                     Thread.sleep(this.pause);
  54.                 } catch(InterruptedException e) {
  55.                     return;
  56.                 }
  57.                
  58.                 System.out.println(this.message);
  59.             }
  60.             System.out.println("Exited the sync block, other thread can now use this resource");
  61.         }
  62.        
  63.     }
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement