Listing 12: File StaticLock.java: Illustrates a class-level lock

class MyThread extends Thread
{
    private int delay;
    private int count;
    public MyThread(String msg, int delay, int count)
    {
        super(msg); // Optional thread name
        this.delay = delay;
        this.count = count;
    }
    public void run()
    {
        for (int i = 0; i < count; ++i)
        {
            try
            {
                Thread.sleep(delay);
                display(getName());
            }
            catch (InterruptedException x)
            {
                // Won't happen in this example
            }
        }
    }
    synchronized static void display(String s)
    {
        for (int i = 0; i < s.length(); ++i)
            System.out.print(s.charAt(i));
        System.out.println();
    }
}

class StaticLock
{
    public static void main(String[] args)
    {
        Thread t1 = new MyThread("DessertTopping", 100, 8);
        Thread t2 = new MyThread("FloorWax", 200, 4);
        t1.start();
        t2.start();
    }
}

/* Output:
DessertTopping
FloorWax
DessertTopping
DessertTopping
FloorWax
DessertTopping
DessertTopping
FloorWax
DessertTopping
DessertTopping
FloorWax
DessertTopping
*/
— End of Listing —