public class CocktailGuest implements Runnable {/** What the guest will say */private final String mumble;/** How many seconds will he/she pause before speaking */private final int pause;/** How long the guest will stay */private final int stay;/** How long the guest has stayed */private int hereFor;/** Constructor */publicCocktailGuest(String mumble,int pause,int stay) {this.mumble = mumble;this.pause = pause;this.stay = stay;
hereFor =0;}/** Execution method */@Overridepublic voidrun() {try{while(hereFor < stay) {
Thread.sleep(pause *1000);
hereFor += pause;
System.out.println(mumble);}}catch(InterruptedException e) {
System.out.println("Something has come up; got to go.");return;}finally{
System.out.println("Good bye.");}}public static voidmain(String args[]) {final int NGUEST =5;var guest =new CocktailGuest[NGUEST];var thread =new Thread[NGUEST];int i =0;
guest[i++] =newCocktailGuest("Can I have another drink?",8,30);
guest[i++] =newCocktailGuest("Nice food!",7,120);
guest[i++] =newCocktailGuest("Ha ha ha...",3,100);
guest[i++] =newCocktailGuest("Hi, I am Maria.",5,60);
guest[i++] =newCocktailGuest("Hello, I am Petros.",15,60);// Create the threadsfor(i =0; i < NGUEST; i++)
thread[i] =newThread(guest[i]);// Start the threadsfor(i =0; i < NGUEST; i++)
thread[i].start();}}