2. Objectives • Define a thread. • Create separate threads in a Java technology program, controlling the code and data that are used by that thread. • Control the execution of a thread and write platform independent code with threads. • Describe the difficulties that might arise when multiple threads share data. • Use wait and notify to communicate between threads. • Use synchronized to protect data from corruption.
3.
4.
5.
6. Example :- Web browser Scroll a page while its downloading an applet Play animation and sound concurrently Print a page in the background
7. Multitasking The ability to execute more than one task at the same time. The terms multitasking and multiprocessing are often used interchangeably. Although multiprocessing implies that more than one CPU is involved. In multitasking, only one CPU is involved, but it switches from one program to another so quickly that it gives the appearance of executing all of the programs at the same time.
8.
9.
10.
11.
12.
13.
14. 2.Declare a class that implements the Runnable interface, that class then implements the run method Example (ThreadDemo.java) class PrimeRun implements Runnable { long minPrime; PrimeRun(long minPrime) { this.minPrime = minPrime; } public void run() { // compute primes larger than minPrime } }
20. Running This is the state a thread is in when the thread scheduler selects it (from the runnable pool) to be the currently executing process. A thread can transition out of a running state for several reasons,
21.
22.
23.
24.
25.
26.
27.
28.
29. The overloaded run(String s) method will be ignored by the Thread class unless you call it yourself. The Thread class expects a run() method with no arguments, and it will execute this method for you in a separate call stack after the thread has been started. With a run(String s) method, execution won't happen in a new thread of execution with a separate call stack. It will just happen in the same call stack as the code that you made the call from, just like any other normal method call.
30.
31.
32.
33. A race condition is a situation in which two or more threads or processes are reading or writing some shared data, and the final result depends on the timing of how the threads are scheduled,