**Multithreaded Programming**
  • Process-based multitasking is the feature that allows your computer to run two or more programs concurrently.

  • processbased multitasking enables you to run the Java compiler at the same time that you are using a text editor or visiting a web site.

  • In process-based multitasking, a program is the smallest unit of code that can be dispatched by the scheduler.

  • In thread-based multitasking a thread is the smallest unit of dispatchable code.

  • In these multithreaded a single program can perform two or more tasks.

Example:

  • A program-text editor can format at same time that is printing.

  • Process based-it deals with big picture.

  • Thread based-enable the details of picture.

  • Multithreading enables you to write the program that use the maximum use of processing power.

  • In general, in a single-threaded environment, when a thread blocks (that is, suspends execution) because it is waiting for some resource, the entire program stops running.

  • Multithreading allows animation loops to sleep for a second between each frame without causing whole system to pause.

  • When a thread blocks in a Java program, only the single thread that is blocked pauses.

  • All other threads continue to run.

  • Threads exist in several states.

  • A thread can be running.

  • It can be ready to run as soon as it gets CPU time. A running thread can be suspended, which temporarily halts its activity.

  • A suspended thread can then be resumed, allowing it to pick up where it left off.

  • A thread can be blocked when waiting for a resource. At any time, a thread can be terminated, which halts its execution immediately.

  • Once terminated, a thread cannot be resumed.

Thread priorities:

  • The act of taking control of the operating system from one task and giving it to another task is called preempting.

  • Thread priority is used to determine when to switch from one task to another.These are controlled by the context switch.

Context Switch rule:

1.by relinquish control(randomly)

2.higher priority

  • For operating systems such as Windows, threads of equal priority are time-sliced automatically in round-robin fashion.

Synchronization:

  • In Java each object has its own implicit monitor that is automatically entered when one of the object’s synchronized methods is called.

  • Once a thread is inside a synchronized method, no other thread can call any other synchronized method on the same object.

  • This enables you to write very clear and concise multithreaded code because synchronization support is built into the language.

Messaging:

  • By contrast, Java provides a clean, low-cost way for two or more threads to talk to each other via calls to predefined methods that all objects have.

Java Thread class and Runnable Interface:

  • Java multithreading is built upon the thread class,upon its methods and its companion interface and runnable.
  • To create a new thread either your program will extend thread or runnable interface.

Main thread:

  • When a Java program starts up, one thread begins running immediately.

  • This is usually called the main thread of your program.

Reason:

1.It is the thread from which other “child” threads will be spawned.

2.The last thread to finish execution because it performs various
shutdown actions.

Example:

class CurrentThreadDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " + t);
try {
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
}
  • The current thread (main thread) is obtained by calling currentThread( ) and this reference is stored in the local variable t.

  • The program then calls setName( ) to change the internal name of the thread.

  • Information about the thread is then redisplayed.

  • A loop counts down from five, pausing one second between each line.

  • The pause is accomplished by the sleep( ) method.

  • The argument to sleep( ) specifies the delay period in milliseconds.

  • Notice the try/catch block around this loop.

  • The sleep( ) method in Thread might throw an InterruptedException.

Example:

        final void setName(String threadName)
        final String getName( )
  • Here, threadName specifies the name of the thread.

  • You can set the name of a thread by using setName( ).

  • You can obtain the name of a thread by calling getName( ).

Creating Thread:

  • You can implement the Runnable interface.

  • You can extend the Thread class, itself.

  • Implementing Runnable:

  • To implement Runnable, a class need only implement a single method called run( ), which is declared like this

                            public void run()
  • Inside run( ) you will define the code that constitutes the new thread and run( ) establishes the entry point for another concurrent thread of execution
                      Thread(Runnable threadOb, String threadName)
  • After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread.

  • In this constructor, threadOb is an instance of a class that implements the Runnable interface.

  • This defines where execution of the thread will begin.

  • The name of the new thread is specified by threadName.

  • The main thread must be the last thread to finish running.

  • In fact, for some older JVMs, if the main thread finishes before a child thread has completed, then the Java run-time system may “hang.”

                  t = new Thread(this, "Demo Thread");
  • Passing this as the first argument indicates that you want the new thread to call the run( ) method on this object.

  • Start( ) is called, which starts the thread of execution beginning at the run( ) method.

  • This causes the child thread’s for loop to begin.

  • Calling start( ), NewThread’s constructor returns to main( ).

Extending Thread:

  • The second way to create a thread is to create a new class that extends Thread,and then to create an instance of that class.

Example:

// Create a second thread by extending Thread
class NewThread extends Thread {
NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
  • In these the thread extended by
            public Thread(String threadName)
  • threadName specifies the name of the thread.

Creating Multiple Threads:

  • Multiple acts in only two threads: the main thread and one child thread.

Example:

// Create multiple threads.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo {
public static void main(String args[]) {
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try {
// wait for other threads to end
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

Using isAlive( ) and join( ):

  • Two ways exist to determine whether a thread has finished. First, you can call isAlive( ) on the thread.

  • This method is defined by Thread and its general form is shown here:

                  final boolean isAlive( )
  • The isAlive( ) method returns true if the thread upon which it is called is still running.

  • It returns false otherwise.

  • While isAlive( ) is occasionally useful, the method that you will more commonly use to wait for a thread to finish is called join( ),shown here:

                  final void join( ) throws InterruptedException

Example:

class NewThread implements Runnable {
String name;                 // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start();                  // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class DemoJoin {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
System.out.println("Thread One is alive: "
ob1.t.isAlive());
System.out.println("Thread Two is alive: "
ob2.t.isAlive());
System.out.println("Thread Three is alive: "
ob3.t.isAlive());
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: " + ob1.t.isAlive());
System.out.println("Thread Two is alive: " + ob2.t.isAlive());
System.out.println("Thread Three is alive: " + ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
}

Thread priority:

  • Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run.

  • In theory, over a given period of time, higher-priority threads get more CPU time than lower-priority threads.

  • To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.

                        final void setPriority(int level)
  • Here, level specifies the new priority setting for the calling thread. The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY.

  • In these normal priorty can be set as average values.

  • These priorities are defined as static final variables within Thread.

Synchronization:

  • When two or more threads need access to a shared resource then they need some way to ensure that the resource will be used by only one thread at a time.

  • The process by which this is achieved is called synchronization.

  • Key to synchronization is the concept of the monitor.

  • A monitor is an object that is used as a mutually exclusive lock.

  • Only one thread can own a monitor at a given time.

  • When a thread acquires a lock, it is said to have entered the monitor.

  • All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor.

Using Synchronized Methods:

  • To enter an object’s monitor, just call a method that has been modified with the synchronized keyword
  • To all other thread try to call it on the same instance have to wait in the thread inside.
  • To exit the monitor the relinquish control have to allow the next waiting thread.

Synchronized Statements:

  • You want to synchronize access to objects of a class that was not designed for multithreaded access.
  • In these class is created by third party so no access to source code due to unidentified(knowned)
  • And then you simply put calls to the methods defined by this class inside a synchronized block.

This is the general form of the synchronized statement:

synchronized(objRef) {
// statements to be synchronized
}

Example:

// synchronize calls to call()
public void run() {
synchronized(target) { // synchronized block
target.call(msg);
  • In these Synchronized statements is used in caller run()method.

Interthread Communication:

  • The preceding examples unconditionally blocked other threads from asynchronous access to certain methods.
  • Its main purpose is allowing synchronized threads to communicate each other.
  • In critical level the thread is paused and then another thread is allowed to critical level to be executed.
  • Wait(): Tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ) or notifyAll( ).
  • Notify(): Wakes up a thread that called wait( ) on the same object.
  • NotifyAll(): Wakes up all the threads that called wait( ) on the same object. One of the threads will be granted access.

Deadlock:

  • Deadlock in java is a part of multithreading.

  • Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread.

  • Both threads are waiting for each other to release the lock, the condition is called deadlock.

  • Representation of thread:

Suspending, Resuming, and Stopping Threads:

  • These are also called threadgroup in Java.
  • Because you can’t now use the suspend( ), resume( ), or stop( ) methods to control a thread.
  • You might be thinking that no way exists to pause, restart, or terminate a thread. But, fortunately, this is not true.
  • Instead, a thread must be designed so that the run( ) method periodically checks to determine whether that thread should suspend, resume, or stop its own execution.
  • This is accomplished by establishing a flag variable that indicates the execution state of the thread.
  • As long as this flag is set to “running,” the run( ) method must continue to let the thread execute.
  • If this variable is set to “suspend,” the thread must pause. If it is set to “stop,” the thread must terminate.

Obtaining a thread state:

  • The thread state defined by

                                   Thread.State getState( )
    
  • It returns a value of type Thread.State that indicates the state of the thread at the time at
    which the call was made.

  • State is an enumeration defined by Thread. (An enumeration is a list of named constants)

  • Value State

  • BLOCKED :A thread that has suspended execution because it is waiting to acquire a lock.

  • NEW A thread that has not begun execution.

  • RUNNABLE A thread that either is currently executing or will execute when it gains access to the CPU.

  • TERMINATED A thread that has completed execution.

  • TIMED_WAITING A thread that has suspended execution for a specified period of time, such as when it has called sleep( ). This state is also entered when a timeout version of wait( ) or join( ) is called.

  • WAITING A thread that has suspended execution because it is waiting for some action to occur.

  • Thread.State ts = thrd.getState();

  • These sequence determine the thread called thrd in a runnable state at the time getstate().

Using Multithreading:

  • If you create too many threads, you can actually degrade the performance of your program rather than enhance it.
  • It also use context switching it will rather predict the changing the context and spend more time in your program.
  • so use individual threads in multithreading to create efficient in your program.

results matching ""

    No results matching ""