655 13 b Java Threads

download 655 13 b Java Threads

of 9

Transcript of 655 13 b Java Threads

  • 8/4/2019 655 13 b Java Threads

    1/9

    Mathis Introduction to Java (V. 2001.02.a) Slide 1

    Threads

    Threads vs. Processes

    Thread Creation by Implementing Runnable Creating Threads by Subclassing

    Advantages of using Threads

    Thread States

    Using join()

    Synchronization wait() and notify()

  • 8/4/2019 655 13 b Java Threads

    2/9

    Mathis Introduction to Java (V. 2001.02.a) Slide 2

    Threads vs. Processes

    A computer is composed of several distinct parts one of which is the

    Central Processing Unit (CPU) When a program is executing, each of the instructions that compose theprogram is fetched from memory into the CPU for processing. Thisprogram in execution is called a process.

    It is usually said that a modern computer can process many processesconcurrently. This is called multi-processing. In reality this means thatmany processes are in various states of execution in any single instant.

    However when a computer has a single CPU, then in any given instant,only a single instruction can be executed. Thus true multi-processing canonly be achieved when a computer has more than one processor.

    On a single CPU computer, the fact that many processes are in variousstates of execution at a single instant is known as multi-programming.Each process has its own variables.

  • 8/4/2019 655 13 b Java Threads

    3/9

    Mathis Introduction to Java (V. 2001.02.a) Slide 3

    Threads vs. Processes

    The ability of a single process to spawn multiple execution paths is

    called multi-threading. Each path is called a thread. A thread is alsoreferred to as a lightweight process. Unlike a process, each threadshares the same set of data (variables). If two threads access this dataat the same time, synchronization problems can occur.

    Generally, multi-threading is a blessing since it allows the same programto handle multiple events concurrently

    When threads are used: a process can e.g.:

    Load an image while it is making a calculation

    Garbage-collect behind the scenes while executing the main path ofthe program

    Send data over a network while it is filling a rectangle New thread can be created by instantiating a Thread object as follows:MyObject m = new MyObject();Thread t = new Thread(m);

    where m is an object from a class which implements the Runnableinterface and as such must provide a run() method.

  • 8/4/2019 655 13 b Java Threads

    4/9

    Mathis Introduction to Java (V. 2001.02.a) Slide 4

    Thread Creation by Implementing Runnable

    A thread is a virtual program in execution. When you create a newthread, you are creating a context for a program, which includes data,memory, and a CPU. The thread will execute the run() method forwhichever object is passed to the Thread constructor. The data forthis execution context is the data for the Object m.

    The above code simply creates a thread. To begin the runnable lifetimeof a thread, you must call the following method from the Thread class:

    public native synchronized void start(); The entire process is shown below:

    Class MyObject implements Runnable {// perhaps some data herepublic MyObject() { }public void run() { System.out.println(got here); } }

    public class TestMyObject {public static void main(String args[]) {MyObject m = new MyObject();Thread t = new Thread(m);t.start(); }

    }

  • 8/4/2019 655 13 b Java Threads

    5/9

    Mathis Introduction to Java (V. 2001.02.a) Slide 5

    Thread Creation by Implementing Runnable

    When you call the start() method of the Thread class, the JVM

    performs some necessary initialization for this thread and then callsthe run() method of the threaded object.

    The result is that two threads are running concurrently:

    The main thread

    And the other thread, which is executing in the run() method

    Soon we will discuss another way of creating a thread using subclassing.In those cases, subclasses of Thread should override the Thread run()method.

    Once the start() method has been called, the run() method is called bystart, and the Thread is off and running, executing the code inside the

    run() method. When the run() method terminates, the thread is dead.

  • 8/4/2019 655 13 b Java Threads

    6/9

    Mathis Introduction to Java (V. 2001.02.a) Slide 6

    Creating Threads by Subclassing

    The Java.lang.Thread class implements the Runnable interface. Thus

    another way to create a thread is to create a subclass of Thread andoverride the run() method.

    class Another extends Thread {public Another(String s) {

    super(s);

    }public void run() {

    for (int j=0; j

  • 8/4/2019 655 13 b Java Threads

    7/9

    Mathis Introduction to Java (V. 2001.02.a) Slide 7

    Creating Threads by Subclassing

    In this (the subclassing) approach there is only one class involved, the

    subclass. Which approach is better? Some might argue that to use subclassing isan OO violation since a subclass should represent the is-a relationship.

    However, if we have an applet, we are already subclassing, and thus wemust use the implements Runnable technique because of the multipleinheritance exclusion in Java.

    By using subclassing, the code can be easier to understand and toimplement since there is only one new class involved.

    Thus there is no hard and fast rule unless you are writing applets.

    The easiest way to see the advantage of threading is to examine aprogram written once without threads and then to examine the rewriteusing threads.

  • 8/4/2019 655 13 b Java Threads

    8/9

    Mathis Introduction to Java (V. 2001.02.a) Slide 8

    Thread States

    A thread can be in various states during its lifetime:new runnable blocked dead

    Various thread methods control the state in which the thread exists.We have seen a few of these methods such as run() and start()methods.

    Other methods of the Thread class are:

    public statis void yield()

    causes the currently executing thread object to tempoarily pauseand allow other threads to execute.public final void setPriority(int newpr)

    sets the priority of this thread to the new priority newpr

    public static void sleep(long millis)

    throws InterruptedException

    causes the currently executing thread to sleep for the specifiednumber of milliseconds

    public static Thread currentThread()

    returns a reference to the currently executing thread object

  • 8/4/2019 655 13 b Java Threads

    9/9

    Mathis Introduction to Java (V. 2001.02.a) Slide 9

    Thread States

    public final String getName()

    returns this threads namepublic final void join() throws Interrupted Exceptionwaits for this thread to diepublic final boolean is Alive()

    tests if this thread is alive; a thread is alive if it has been startedand has not yet died