The Lifecycle of a Thread

We have already covered how a thread is created, and how the start() method inherited from Thread causes execution to start in its run() method. An individual thread dies when execution falls off the end of run() or otherwise leaves the run method (through an exception or return statement).

If an exception is thrown from the run method, the runtime system prints a message saying so, the thread terminates, but the exception does not propagate back into the code that created or started the thread. What this means is that once you start up a separate thread, it doesn't come back to interfere with the code that spawned it.

Priorities

Threads have priorities that you can set and change. A higher priority thread executes ahead of a lower priority thread if they are both ready to run.

Java threads are preemptible, meaning that a running thread will be pushed off the processor by a higher priority thread before it is ready to give it up of its own accord. Java threads might or might not also be time-sliced, meaning that a running thread might share the processor with threads of equal priority.

Since a programmer cannot assume that time-slicing will take place, the careful programmer assures portability by writing threaded code that does not depend on time-slicing. The code must cope with the fact that once a thread starts running, all other threads with the same priority might become blocked. One way to cope with this would be to adjust thread priorities on the fly. That is not recommended because the code will cost you a fortune in software maintenance.

A better way is to yield control to other threads frequently. CPU-intensive threads should call the yield() method at regular intervals to ensure they don't hog the processor. This won't be needed if time-slicing is made a standard part of Java. Yield allows the scheduler to choose another runnable thread for execution.

Java thread priorities run from 1 (lowest) to 10 (highest). Threads start off with the same priority as their parent thread (the thread that created them), and you can adjust the priority as follows:

t1.setPriority ( t1.getPriority() +1 );

On operating systems that have priorities, most users cannot adjust their processes to a higher priority (because they can gain an unfair advantage over other users of the system).[2] There is no such inhibition for threads, because they all operate within one process. The user is competing only with himself or herself for resources.


[2] Hence, the infamous message from the system operator, “I've upped my priority, now up yours.”

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.41.205