CSCE 314 Lecture 34

From Notes
Jump to navigation Jump to search

« previous | Monday, November 21, 2011 | next »


Java Concurrency

Threads used to execute concurrent tasks.

Java Thread and Runnable:

public interface Runnable
{
    public void run();
}

public class GreetingRunnable implements Runnable
{
    public GreetingRunnable(String aGreeting)
    {
        greeting = aGreeting;
    }

    public void run()
    {
        try {
            for (int i=0; i<REPETITIONS; i++) {
                Date now = new Date();
                System.out.println(now + " " + greeting);
                Thread.sleep(DELAY)
            }
        } catch (InterruptedException exception) {
            // Interrupting a sleeping thread (Ctrl+C) raises an exception
        }
    }

    private String greeting;
    private static final int REPETITIONS = 10;
    private static final int DELAY = 100;
}

public class TestGreeting
{
    public static void main(String[] args)
    {
        GreetingRunnable r1 = new GreetingRunnable();
        GreetingRunnable r2 = new GreetingRunnable();
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);
        t1.start();
        t2.start();
    }
}
Note: We don't have any control over which thread is running at a given time (up to OS scheduler).

Updating/accessing shared memory at the same time (recall "side effects" from our discussion of Haskell) can lead to "race condition".

We can ask threads to wait for data from another thread.

Optionall extend Thread:

public class MyThread extends Thread {
    public void run() { /* ... */ }
}

Thread t = new MyThread(); // not passing a runnable to constructor
t.start() // runs built-in run() function.


Stopping Threads

  • when run() returns
  • call to Thread::interrupt() method: sets interrupted() flag
    • look at flag with Thread.interrupted(), which clears the flag. This allows thread to clean up
    • convention: surround entire body of run method with try-catch block.
    • Thread.stop() is deprecated as it is too dangerous
public void run()
{
    try {
        // ... do stuff
        if (!Thread.interrupted()) {
            // ... do more stuff
        } else {
            System.out.println("Interrupted");
            throw new InterruptedException();
        }
        Thread.sleep();
    } catch (InterruptedException ex) {
        System.out.println("Interrupted and ousted");
        // this occurs if interrupt received while sleeping
    }
}


Thread States

new
just created; not yet started
runnable
after invoking start(), not yet scheduled
running
executing
blocked
waiting for resource; sleeping for a set period of time; returns back to runnable state
dead
run() has returned; cannot be restarted


Synchronization

Thread safety
software element is guaranteed to exhibit correct behavior while executed concurrently by more than one thread

Fields of an object/class always maintain a valid state (class invariant) even when used concurrently