CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Threads

Threads
Manipulate threads
Interrupt a thread

How to interrupt a thread

  • One thread can interrupt another thread by calling the second thread's interrupt method.
  • A thread should frequently check its isInterrupted method to see if it has been interrupted.
  • If a thread is interrupted while it is sleeping, InterruptedException is thrown. In this case, the isInterrupted method won't indicate that the thread has been interrupted.

A Counter application that uses an interruptable thread

import java.util.Scanner;

public class CountInterruptApp
{
    public static void main(String[] args)
    {
        Thread counter = new Counter();     // instantiate the counter thread
        counter.start();                    // start the counter thread

        Scanner sc = new Scanner(System.in);
        String s = "";
        while (!s.equals("stop"))           // wait for the user to enter "stop"
            s = sc.next();
        counter.interrupt();                // interrupt the counter thread
    }
}

class Counter extends Thread
{
    public void run()
    {
        int count = 0;
        while (!isInterrupted())
        {
            System.out.println(this.getName() + " Count " + count);
            count++;
            try
            {
                Thread.sleep(1000);
            }
            catch (InterruptedException e)
            {
                break;
            }
        }
        System.out.println("Counter interrupted.");
    }
}

Console output from the Counter application

Thread-0 Count 0 Thread-0 Count 1 Thread-0 Count 2 stop Counter interrupted. Press any key to continue . . .
Previous | Put a thread to sleep | Set a thread's priority | Interrupt a thread | Next