Вы находитесь на странице: 1из 9

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()

Mathis Introduction to Java

(V. 2001.02.a)

Slide 1

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 the program is fetched from memory into the CPU for processing. This program in execution is called a process. It is usually said that a modern computer can process many processes concurrently. This is called multi-processing. In reality this means that many 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 can only be achieved when a computer has more than one processor. On a single CPU computer, the fact that many processes are in various states of execution at a single instant is known as multi-programming. Each process has its own variables.

Mathis Introduction to Java

(V. 2001.02.a)

Slide 2

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 also referred to as a lightweight process. Unlike a process, each thread shares the same set of data (variables). If two threads access this data at the same time, synchronization problems can occur. Generally, multi-threading is a blessing since it allows the same program to 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 of the 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 Runnable interface and as such must provide a run() method.
Mathis Introduction to Java (V. 2001.02.a) Slide 3

Thread Creation by Implementing Runnable


A thread is a virtual program in execution. When you create a new thread, you are creating a context for a program, which includes data, memory, and a CPU. The thread will execute the run() method for whichever object is passed to the Thread constructor. The data for this execution context is the data for the Object m. The above code simply creates a thread. To begin the runnable lifetime of 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 here public 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(); } }
Mathis Introduction to Java (V. 2001.02.a) Slide 4

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 calls the 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 by start, and the Thread is off and running, executing the code inside the run() method. When the run() method terminates, the thread is dead.

Mathis Introduction to Java

(V. 2001.02.a)

Slide 5

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 and override the run() method. class Another extends Thread { public Another(String s) { super(s); } public void run() { for (int j=0; j<5; j++) System.out.println(getName()+ +j); } public static void main(String a[]) { Thread t = new Another(Thread 1); t.start(); Thread r = new Another(Thread 2); r.start(); } }
Mathis Introduction to Java (V. 2001.02.a) Slide 6

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 is an OO violation since a subclass should represent the is-a relationship. However, if we have an applet, we are already subclassing, and thus we must use the implements Runnable technique because of the multiple inheritance exclusion in Java. By using subclassing, the code can be easier to understand and to implement 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 a program written once without threads and then to examine the rewrite using threads.

Mathis Introduction to Java

(V. 2001.02.a)

Slide 7

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 pause and 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 specified number of milliseconds public static Thread currentThread() returns a reference to the currently executing thread object
Mathis Introduction to Java (V. 2001.02.a) Slide 8

Thread States
public final String getName() returns this threads name public final void join() throws Interrupted Exception waits for this thread to die public final boolean is Alive() tests if this thread is alive; a thread is alive if it has been started and has not yet died

Mathis Introduction to Java

(V. 2001.02.a)

Slide 9

Вам также может понравиться