Παράδειγμα χρήσης νημάτων


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 */
    public CocktailGuest(String mumble, int pause, int stay) {
        this.mumble = mumble;
        this.pause = pause;
        this.stay = stay;
        hereFor = 0;
    }

    /** Execution method */
    @Override
    public void run() {
        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 void main(String args[]) {
        final int NGUEST = 5;
        var guest = new CocktailGuest[NGUEST];
        var thread = new Thread[NGUEST];

        int i = 0;
        guest[i++] = new CocktailGuest("Can I have another drink?", 8, 30);
        guest[i++] = new CocktailGuest("Nice food!", 7, 120);
        guest[i++] = new CocktailGuest("Ha ha ha...", 3, 100);
        guest[i++] = new CocktailGuest("Hi, I am Maria.", 5, 60);
        guest[i++] = new CocktailGuest("Hello, I am Petros.", 15, 60);

        // Create the threads
        for (i = 0; i < NGUEST; i++)
            thread[i] = new Thread(guest[i]);
        // Start the threads
        for (i = 0; i < NGUEST; i++)
            thread[i].start();
    }
}