Showing posts with label Threads. Show all posts
Showing posts with label Threads. Show all posts

Friday, February 13, 2009

Thread creation

Multitasking:
* Executing several tasks simultaneously is the concept of Multitasking.
* The main objective of multitasking is to decrease response time of the system, so that the performance of the system will increase.

Process Based Multitasking:-

* Executing several tasks simultaneously where each task is a independent program.
* Example typing a java program in the Editor, playing MP3 player, Downloading a file from the internet
* All the tasks are independent of each other and executes simultaneously.
* This type of multitasking is useful at OS level.
* CGI fallows process based multitasking.

Thread Based Multitasking:-

* Executing several tasks simultaneously, where each task is a separate inependent part of the same program. That independent part is called the Thread.
* Servlets fallowThread Based MultiTasking.
* Java itself provide support for multithreading by introducing several library classes.
* We can use in games/animation programme.
* Creating a thread in two ways.

1. By extending Thread
2. By implementing Runnable

Methods used to prevent a thread from execution:

* yield()
* join()
* sleep()
* Synchronization
* InterThread communication (wait, notify, notifyAll)

Defining, Instantiating and starting Thread by extending Thread class:
class MyThread extends Thread
{
public void run()
{
System.out.println("child job”);
}
}
Here run method is the heart of thread where you have to define the job.
class Sample
{
public static void main(String a[])
{
MyThread t=new MyThread();
t.start(); //starting a thread
System.out.println(“Main thread job”);
}
}
The above program executes well.it gives the output mainthread job,child job,.........
Difference between t.start() & t.run()?
• If we call t.start(), it will create a new Thread and that thread is responsible for execution of run().
• If we call t.run(), mo new thread will create, the main thread only will execute run(), just like a normal method.
• In case of t.start() output we can’t expect
• In case of t.run() output Child Thread 10 times fallowed by main thread 10 times.

Thread class start():-
public void start()
{
1. Registering our thread with the thread scheduler then only thread scheduler allocate CPU and memory type of resources for this new thread also.
2. calls run()
}
If we over ride start method in the above example:
--->public void start()
{
System.out.println(“start method”);// start method 1 time, main thread 10 times
}
--->public void start()
{
super.start();
System.out.println(“start method”);// start method child & main thread alternatively
}
class MyThread extends Thread
{
public static void main(String a[])
{
MyThread t=new MyThread();
t.start();
}
}
• Thread class run() has empty implementation that’s why we are getting no output.
Defining, Instantiating and starting Thread by implementing Runnable
Ex: class MyRunnable implemts Runnable
{
public void run()
{
for(int i=0; i<=10 ;i++)
System.out.pritnln(“child thread”);
}
}
class ThreadDemo
{
public static void main(String a[])
{
MyRunnable r=new MyRunnable();
r.start(); // compile time errror
Thread t=new Thread(r); ---> Target Runnable
for(int i=0 ; i<=10 ; i++)
{
System.out.println(“main thread”);
}
}
} In the above example instead of r.start we place r.run(); //childThread (no new thread will create ) In the above example we place the

* t.start(); //valid (new thread will create child thread)
* t.run(); // child thread (no new thead will create)

• Among the above two probabilities of creating thread it is highly recommended to use implements Runnable mechanism.
• In the first case ( extends thread), our thread class extends Java.Lang.Thread, hence no chance of extending any thing else. Hence we are missing, the key benefit of oop’s concept ie., inheritance.
Lifecycle of Thread:





• Once the thread is started, there is no chance of starting the same thread once again.
Violation leads to RTE saying Illegal Thread State Exception”.
• Thread t= new Thread();
t.start(); //no o/p

Thread class Constructors:
1. Thread();
2. Thread(Runnable r);
3. Thread(String name);
4. Thread(Runnable r, String name);
5. Thread(ThreadGroup g, String name);
6. Thread(ThreadGroup g, Runnable r);
7. Thread(ThreadGroup g, Runnable r, String name);
Ex:- // Test king
class MyThread extends Thread
{
public void run()
{
System.out.println(“run”);
}
}
class ThreadDemo
{
public static void main(String a[])
{
MyThread t= new MyThread();
Thread t1=new Thread(t);
t1.start();
// t1.run(); ----> It is just like a method no new thread will create
}
}
Setting & getting the name of a thread:
Thread class contain the fallowing methods for setting & getting the name of the Threads..

* public final String getName();
* public final void setName(String s);

Thread class yield , join , sleep.

Thread Priorities:
• Thread class contains the fallowing methods for setting and getting priority of a thread.
public final int getPriority();
public final void setPriority(int i);
• The valid range for the thread priorities 1 to 10 (1 is atleast and 10 is the highest)
• Thread class contains the fallowing predefined priority constraints.
MAX-PRIORITY ----> 10
NORM-PRIORITY ----> 5 (default)
MIN-PRIORITY ----> 10
• If you are trying to set the priority as greater than 10 or lessthan1, then we will get a RTE saying “Illegal Argument Exception”
Example:
class MyThread extends Thread
{}
class Sample
{
public static void main(String a[])
{
Thread.currentThread().setPriority(10);
System.out.pritnln(Thread.currentThread().getPriority());
MyThread t= new MyThread();
System.out.pritnln(t.getPriority());//10 10
}
}
• The default priority for the maintained is 5. But we are allowed to change the prority by using setPriority()
• The priority of any the thread is inherited from the parent thread.
• Thread scheduler uses these proroites to allocate CPU. The thread which is having highest priority will get executes first. t1.setPriority(10);
Yield() :

  • We can prevent a thread from execution by using one of the fallowing methods.
1. yield()
2. join()
3. sleep()
• The thread which is executing yield() causes the current thread temperarly pause and allow other waiting threads of same or high priority to execute.
• If there is no waiting thread, the same thread will execute immediately.
• If all the remaining threads are having low priority, then the same thread once again will execute.
Method Signature:-
public static native yield();



• If the thread calls yield(), the thread going to ready state.
yield method example:
Class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.pritnln(“child thread”);
Thread.yield();
}
}
}
class SampleDemo
{
public static void main (String a[])
{
MyThread t = new MyThread();
t.start();
for(int i=0;i<10;i++);
{
System.out.pritnln(“main thread”);
}
}
}

• The yield() depends upon underlying platform. Some platforms may not support .Breaks java’s programme independency.
join:
• If any executing thread calls join method on amy thread t, the current thread will go to the blocked state until t completes.
Method Signature:
public final void join() throws InterruptedException
public final void join(long ms)throws InterruptedException
public final void join(long ms, int nanosec)throws InterruptedException


join Example:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(“sita thread”);
try
{
Thred.sleep(1000);
}
catch(InterruptedException e){}
}
}
}
class JoinDemo
{
public static void main(String a[])
{
MyThread t=new MyThread();
t.start();
t.join(); //or t.join(3000);
for(int i=0;i<10;i++);
{
System.out.println(“Rama thread”);
}
}
}
sleep():-
• The thread which is executing sleep() will go to the sleep for the specified amount of time.
MethodSignature:
public static void sleep(long ms) throws InterruptedException
public static void sleep(long ms, int nanoseconds)throws InterruptedException



sleep example:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(“child thread”);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e){}
}
}
}
class SleepDemo
{
public static void main(String a[])
{
MyThread t=new MyThread();
t.start();
}
}
interrupt():
• The thread can interrupt any sleeping/waiting/blocked for joining by the fallowing thread class method.
public void interrupt(); //this is instance method
interrupt example:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(“child thread”);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(“I got interrupted”);
}
}
}
}
class SleepDemo
{
public static void main(String a[])
{
MyThread t=new MyThread();
t.start();
t.interrupt();
}
}


summsrization table:

Thread Synchronization

Synchronization:

  • The keyword synchronized can be apply only for methods and blocks. Ie., We can’t apply synchronized keyword for the classes and variables.
  • If a method (or block) declared as the synchronized at a time only one thread is allowed to execute that synchronized area on any given object.
Advantage: Prevent data corruption, achieve security.
Limitation: Because of synchronized keyword 2 threads are not allowed to execute concurrently on any object, hence the waiting time of the threads will increase, which results in low performance of the system.
A class can contain both synchronized and non synchronized methods.
  • If a thread calls synchronized method on any object, first this thread got the lock, it is allowed to any synchronized method on that object.
  • If a thread executing any synchronized method on the given object at that time no other thread is allowed to execute any synchronized method on that object.
  • If a thread executing any synchronized method the remaining threads are allowed simultaneously to execute nay non synchronized method on that object.
  • Every Object in java has a lock. At the time of synchronization only the lock concept will conme into the picture.
Synchronization example:-
class Display
{
public synchronized void show(String name)
{
for(int i=0;i<10;i++)
{
System.out.println(“Good Morning:”);
try
{
Thread.sleep(2000);
}
catch(InterruptedException e){}
System.out.println(name);
}
}
}
class MyThread extends Thread
{
Display d;
String name;
MyThread(Display d, String name)
{
this.d=d;
this.name=name;
}
public void run()
{
d.show(name);
}
}
class SynchronizedDemo
{
public static void main(String a[])
{
Display d=new Display();
MyThread t1=new MyThread(d,”java”);
MyThread t2=new MyThread(d,”Sun”);
t1.start();
t2.start();
}
}
output:
good morning : java ......10 times after good morning: sun ......10 times
If we are not putting synchronized keyword we will get some irregular output like
goodmorning :good morning:java good morning:sun..........like that

Class Level lock:
• If you want to execute any static synchronized method, first the thread should required a class level lock.
• If a thread has class level lock, it is allowed to execute any stock synchronized method. During that time no other thread is allowed to execute any static synchronized method. But the remaining threads are allowed to execute any static non synchronized methods of the same class.

thread communication wait , notify , notifyall

Two threads can communicate with each other by using wait(), notify(), notifyall() methods Signatures.
Public final void wait() throw interepedException.
Public final native void wait(longms)throws InterruptedException.
Public final void wait(long ms,int ns)throws InterruptedException.
Public final native void notify();
Public final native void notifyAll();
Why this methods are in objclass instead of threadclass?
Wait(),notify();notifyAll() cantain in object class,not in the thread class.because these methods can be applied on common shared object,not on the thread.
Inorder to call wait(),notify(),notifyAll() on an object, we should be the owener of that object.
We are allowed to call wait(),notify(),notifyAll() methods from the synchronized context only(then only we will get the lock of that object and we will beome owner of that object )
If we call wait(),notify(),notifeAll() from non synchronized context,we will get a run time Exception saying”illegal monitar state Exception: not a owner”



If the thread call wait()method,first it releases the lock and thenit will go for waiting state, if the waiting thread gets ‘notification call’ or time expired’ or’got interruption’ then it will go for another blocked state for getting lock.
Once the thread got the lock, it will go to the ready state.
After calling wait method immedeatly releases the lock but after giving notify call the thread may not the lock immediately.
The only method which causes the releasing of lock is wait() method.
But in the case of sleep(),loin() or yield() the thread never releases the lock.
Method results release of lock:
Wait()
Join()
Sleep()
Yield()
Notify() // releases the lock, but may not immediatly
noifyAll()
A thread can acquire more then one lock at time .a thread releses the lock of an object on which it calls the wait()method .it run releses all the locks.
Example:
Class Thread A
{
Public static void main(string[]args)throws interrupted Exception
{
ThreadB b =new threadB();
b.start();
synchronized(b)//thread got lock
{
System.out.pritnln(“iam calling wait method”);
b.wait();
System.out.pritnlnpln(“I got notification);
}
System.out.pritnlnpln(b.total);
}
}
Class ThreadB extends Thread
{
Int total=0;
Public void run()
{
Synchronized (this).//.thread got lock
{
System.out.pritnln(“iam starting calculation”);
for(int i=0;i<=1000;i++)
{
Total=total+i;
}
System.out.pritnln(“iam giving notification call”);
notify();//thread releases lock again
}
}
} //500 500.
Flow -- > 0 -->1 --> 2 --> 3 --> 4 ---> 5

Daemon Thread

The threads which are executing in the background to provide support for user defined threads are called daemon threads.
Ex: garbage callector
Thread class contain the following method for checking whether the given thread is daemon or not
Public final Boolean isDaemon();
Daemon thread Example:
Class DaemonThread
{
Public static void main(string []args)
{
s.o.pln(thread .currentThread().isDaemon());
}
}
Usually daemon threads runnigg with low priority but based on our requirement we can
give high priority also,The daemon nature is inherited from the parent..ie of the parent is the daemon thread then the child also daemon thread and the parent n non-daemon by default child also non-daemon.
Based on our requirement we are allowed to change the daemon nature of any thread b the following method.
Public final setDaemon(Boolean b);
if b is true the thread will become daemon otherwise non-Daemon
Example:class sample extends thread
{
{
Public static void main(String[] a)
{
MyThread t=new MyThread();
t.start();
t.setDaemon(true);
System.out.println(t.asDaemon());
we are not allowed to change Daemon nature after starting a thread,validation leads to RTE saying “illegal thread state Exception”
ie we are not allowed to change Daemon nature of main method it is already started at the beginning only.
Whenever the last non-Daemon thread dead all the Daemon threads will be terminated automatically
Class MyThread extends Thread
{
Public void run()
{
For(int i=0;i<10;i++)
{
s.o.pln(“childmethod”);
try
{
Thread.sleep(2000);
}
Catch(InterruptedException e) {}
}
}
}
Class DaemonThreadExample
{
public static void main(string[]args)threads IE
{
MyThread t=new Thread();
System.out.println(t.isDaemon());
t.setDaemon(true);
t.start();
thread.sleep(5000);
System.out.println(“end of main thread”);
}
}
After starting the thread we are allowed to change the priority of a thread but not allowed to change the Daemon nature.

Thread DeadLock

If two threads are waiting for each other forever,that situation is considered as deadlock.(a lock without key is the deadlock)
We can present the dead lock occurrence but we const resolve.
Dead lock Example:
Class A
{
Public synchrozied void foo(B b)
{
System.out.println(“thread t1 entered into foo”);
try
{
Thread.sleep(2000);
}
catch(IE e){}
System.out.println(“thread t1 calling B’s last method”)
b.last();
}
Public synchronized void last()
{
System.out.println(“a class last method”);
}
}
Class B
{
Public synchronized void bar(A a)
{
System.out.println(“thread t2 entered into bar”);
try
{
Thread.sleep(2000);
{
Catch(intereped Exceptiom e){}
System.out.println(“thread t2 calling Ab last method);
a.last();
}
Public synchronized void last()
{
System.out.println(“B class last method”);
}
}
class DeadlockExample
{
A a=new A();
B b=new B();
DeadLock(){
Thread.currentThread().setName("main thread");
Thread t=new Thread(this);
t.start();
b.bar();
}
Public static void main(string[]args)
{
Deadlock d=new Deadlock();
}
Public void run()
{
a.foo(b);
}
}

thread group

Every Java thread is a member of a thread group. Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once, rather than individually. For example, you can start or suspend all the threads within a group with a single method call. Java thread groups are implemented by the thread group class in the java.lang package.

The runtime system puts a thread into a thread group during thread construction. When you create a thread, you can either allow the runtime system to put the new thread in some reasonable default group or you can explicitly set the new thread's group. The thread is a permanent member of whatever thread group it joins upon its creation--you cannot move a thread to a new group after the thread has been created.

The Default Thread Group:

If you create a new Thread without specifying its group in the constructor, the runtime system automatically places the new thread in the same group as the thread that created it (known as the current thread group and the current thread, respectively). So, if you leave the thread group unspecified when you create your thread, what group contains your thread?

When a Java application first starts up, the Java runtime system creates a ThreadGroup named main. Unless specified otherwise, all new threads that you create become members of the main thread group.

Creating a Thread Explicitly in a Group
A thread is a permanent member of whatever thread group it joins when its created--you cannot move a thread to a new group after the thread has been created. Thus, if you wish to put your new thread in a thread group other than the default, you must specify the thread group explicitly when you create the thread. The Thread class has three constructors that let you set a new thread's group:
public Thread(ThreadGroup group, Runnable target)
public Thread(ThreadGroup group, String name)
public Thread(ThreadGroup group, Runnable target, String name)
Each of these constructors creates a new thread, initializes it based on the Runnable and String parameters, and makes the new thread a member of the specified group. For example, the following code sample creates a thread group (myThreadGroup) and then creates a thread (myThread) in that group.
ThreadGroup myThreadGroup = new ThreadGroup("My Group of Threads");
Thread myThread = new Thread(myThreadGroup, "a thread for my group");
The ThreadGroup passed into a Thread constructor does not necessarily have to be a group that you create--it can be a group created by the Java runtime system, or a group created by the application in which your applet is running.
Thread group Example:
public class ThreadGroupDemo {

class MyThreadGroup extends ThreadGroup {
public void uncaughtException(Thread t, Throwable ex) {
System.err.println("I caught " + ex);
}
public MyThreadGroup(String name) {
super(name);
}
}

public static void main(String[] args) {
new ThreadGroupDemo().work();
}

protected void work() {
ThreadGroup g = new MyThreadGroup("bulk threads");
Runnable r = new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName() + " started");
for (int i=0; i<5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(1776);
} catch (InterruptedException ex) {
System.out.println("Huh?");
}
}
}
};

// Create and start all the Threads
for (int i = 0; i< 10; i++) {
new Thread(g, r).start();
}

// List them.
Thread[] list = new Thread[g.activeCount()];
g.enumerate(list);
for (int i=0; i) {
if (list[i] == null)
continue;
Thread t = list[i];
System.out.println(i + ": " + t);
}
}
}

Friday, February 6, 2009

java Threads

examples Threads