This documentation is archived and is not being maintained.

java.lang.Thread

Visual Studio 2005

Represents an independent stream of execution within a program.


public class Thread implements Runnable

// thread_overview.jsl

public class Program implements Runnable
{
    public static void main(String[] args)
    {
        Program p = new Program();
        p.init();
    }

    public void init()
    {
        try
        {
            // Create a second thread and start it.
            Thread thr2 = new Thread(this);
            thr2.setDaemon(false);
            thr2.setName("Thread 2");
            thr2.setPriority(Thread.MAX_PRIORITY);
            System.out.println("Starting " +
                thr2.getName() + "...");
            thr2.start();

            // Create a third thread and start it.
            Thread thr3 = new Thread(this);
            thr3.setDaemon(true);
            thr3.setName("Thread 3");
            thr3.setPriority(Thread.NORM_PRIORITY);
            System.out.println("Starting " +
                thr3.getName() + "...");
            thr3.start();

            // Display the number of active threads.  This
            // count includes the main thread.
            System.out.println("Active threads = " +
                Thread.activeCount());

            // Wait some time for the child threads to start.
            try
            {
                Thread.sleep(500);
            }
            catch (InterruptedException ex)
            {
                // Ignore the exception here.
            }

            // Interrupt the two sub-threads.
            thr2.interrupt();
            thr3.interrupt();

            // Block until the other threads finish.
            thr2.join();
            thr3.join();
        }
        catch (InterruptedException ex)
        {
            System.out.println(ex.toString());
        }
    }

    // Implements Runnable.run()
    public void run()
    {
        try
        {
            Thread currentThread = Thread.currentThread();
            System.out.println(currentThread.getName() +
                " [daemon = " + currentThread.isDaemon() +
                ", priority = " + currentThread.getPriority() +
                "] is executing.");

            while (true)
            {
                Thread.sleep(500);
            }
        }
        catch (InterruptedException ex)
        {
            Thread currentThread = Thread.currentThread();
            System.out.println(currentThread.getName() +
                " was interrupted: " + ex.toString());
        }
    }
}

/*
Sample Output:
Starting Thread 2...
Starting Thread 3...
Thread 2 [daemon = false, priority = 10] is executing.
Active threads = 3
Thread 3 [daemon = true, priority = 5] is executing.
Thread 3 was interrupted: java.lang.InterruptedException: Thread has been interrupted from a waiting state.
Thread 2 was interrupted: java.lang.InterruptedException: Thread has been interrupted from a waiting state.
*/
Show: