Threads in Java

Threads and Concurrent Execution:

In which expressions are evaluated and statements are executed one after the other: that is onsidered only a single thread of execution, where a thread is an independent sequential activity. A Java program may execute several threads concurrently, that is, potentially overlapping in time. For instance, one part of a program may continue computing while another part is blocked waiting for input.

Multiple Threads:

The main program creates a new thread, binds it to u, and starts it. Now two threads are executing concurrently: one executes main, and another executes run. While the main method is blocked waiting for keyboard input, the new thread keeps incrementing i. The new thread executes yield() to make sure that the other thread is allowed to run (when not blocked).

class Incrementer extends Thread {
public int i;

public void run() {

for (;;) { // Forever
i++; // increment i
yield();
}
}
}
class ThreadDemo {
public static void main(String[] args) throws IOException {

Incrementer u = new Incrementer();
u.start();
System.out.println("Repeatedly press Enter to get the current value of i:");
for (;;) {
System.in.read(); // Wait for keyboard input
System.out.println(u.i);
}
}
}

A thread is created and controlled using an object of the Thread class found in the package java.lang. A thread executes the method public void run () in an object of a class implementing the Runnable interface, also found in package java.lang. To every thread (independent sequential activity) there is a unique controlling Thread object, so the two are often thought of as being
identical.

One way to create and run a thread is to declare a class U as a subclass of Thread, overwriting its (trivial) run method. Then create an object u of class U and call u.start(). This will enable the thread to execute u.run() concurrently with other threads .

Alternatively, declare a class C that implements Runnable, create an object o of that class, create a thread object u = new Thread(o), and execute u.start (). This will enable the thread to
execute o.run() concurrently with other threads. Threads can communicate with each other via shared state, namely, by using and assigning static fields, non static fields, array elements, and pipes . By the design of Java, threads cannot use local variables and method parameters for communication.

RELATED POST:

EXCEPTIONS IN JAVA

No comments:

Post a Comment