Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Lab2 {
- public static void main(String[] args) {
- Runnable joes = new SharingAResource("Eat at Joe's", 10, 2);
- Runnable bills = new SharingAResource("Eat at Bill's", 10, 4);
- Thread j = new Thread(joes);
- Thread b = new Thread(bills);
- j.start();
- b.start();
- System.out.println("Billboard started");
- try {
- j.join();
- b.join();
- } catch (InterruptedException e) {
- return;
- }
- System.out.println("Billboard closed");
- }
- }
- class SharingAResource implements Runnable {
- private String message;
- private int counter;
- private int pause;
- private static Object screen = new Object();
- //constructor
- public SharingAResource(String message, int counter, int pause){
- this.message = message;
- this.counter = counter;
- this.pause = pause * 1000;
- }
- public void run() {
- synchronized(screen) {
- System.out.println("Entered the sync block, no other thread can use this resource");
- for(int i=0; i<counter; i++) {
- try {
- Thread.sleep(this.pause);
- } catch(InterruptedException e) {
- return;
- }
- System.out.println(this.message);
- }
- System.out.println("Exited the sync block, other thread can now use this resource");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement