Thread
--------
Thread is a task.
we can split a single into several tasks called multitasking
life cycle
----------
born state
runnable state yield()
running state start(),run()
blocked state sleep(1000),wait() ,notify() or notifyall()
dead state stop()
isAlive()
it determine whether a thread has finished or not
[it return true if the thread is still running ,otherwise it
return false]
join()
Waits until the thread on which it is called to Terminates
synchronized():-
when two or more thread need access to a shared resource,
they need access to that the resource will be used by only one thread
at a time
deadlock():-
Threads can become blocked and because objects can have synchronized methods that
prevent threads from accessing that object until the synchronization lock is released,
it’s possible for one thread to get stuck waiting for another thread,which in turn
waits for another thread, etc., until the chain leads back to a thread waiting on the
first one. Thus, there’s a continuous loop of threads waiting on each other and no one
can move. This is called deadlock.
============================================
Creating threads
-------------------
Threads are implements in the form of objects that contain a method called run().
The run() method is the heart and soul of any thread.It makes up the entire body
of a thread and is the only method in which the thread's behaviour can be
implemented.
syntax:
public void run()
{
...............................
...............................(statement for implementing thread)
...............................
}
The run() method should be invoked by an object of the concerned thread. This can be achieved by creating the thread and initiating it with the help of another thread method called start().
A new thread can be created in two ways.
1. By creating a thread class:
Define a class that extends Thread class and override its run() method with the code required by the thread.
2. By converting a class to a thread:
Define a class that implements Runnable interface. The Runnable interface has only one method, run(), that is to be defined in the method with the code to be executed by the thread.
Extending the Thread Class
-------------------------------
We can make our class runnable as thread by extending the class java.lang.Thread. This gives us access to all the thread methods directly. It includes the following steps:
1. Declare the class as extending the Thread class.
2. Implement the run() method that is responsible for executing the sequence of
code that the thread will execute.
3. Create a thread object and call the start() method to initiate the thread execution.
Declaring the Class
---------------------
The Thread class can be extended as follows:
class MyThread extends Thread
{
...................
....................
....................
}
Implementing the run() Method
---------------------------------
public void run()
{
..................................
.................................. //Thread code here
.................................
}
Starting New Thread
--------------------------
MyThread aThread=new MyThread();
aThread.start();//invokes run() method
Method Meaning
getName Obtain a thread's name.
getPriority Obtain a thread's priority.
isAlive Determine if a thread is still running
join Wait for thread to terminate
run Entry point for the thread
sleep Suspend a thread for a period of time
start Start a thread by calling its run method.
An Example using the Thread Class
=============================
new A().start();
This is equivalent to:
A threadA=new A();
threadA.start();
//Creating a thread using the thread class
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("From ThreadA:i="+i);
}
System.out.println("Exit from a");
}
}
class B extends Thread
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println("From Thread B:j="+j);
}
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run()
{
for(int k=1;k<=5;k++)
{
System.out.println("From Thread C:k="+k);
}
System.out.println("Exit from C");
}
}
class ThreadTest
{
public static void main(String args[])
{
new A().start();
new B().start();
new C().start();
}
}
----------------------
Stopping and Blocking a Thread
------------------------------------
Stopping a Thread
---------------------
Whenever we want to stop a thread from running further, we may do so by calling its stop() method, like
aThread.stop();
This statement causes the thread to move to the dead state.
Blocking a Thread
--------------------
A thread can be temporarily suspended or blocked from entering into the runnable and subsequently running state by using either of the following thread methods.
sleep() //blocked for a specified time.
suspend() //blocked until further orders
wait() //blocked until certain condition occurs
These method cause the thread to go into the blocked(or not-runnable)state. The thread will return to the runnable state when the specified time is elapsed in the case of sleep(),the resume() method is invoked in the case of suspend(), and the notify() method is called in the case of wait().
Life Cycle of a Thread
-------------------------
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
Newborn State
------------------
When we create a thread object, the thread is born and is said to be in newborn state. The thread is not yet scheduled for running. At this state, we can do only one of the following things with it:
Schedule it for running using start() method
Kill it using stop() method
Runnable State
----------------
The runnable state means that the thread is ready for execution and is waiting for the availability of the processor. That is, the thread has joined the queue of threads that are waiting for execution. If all threads have equal priority, then they are given time slots for execution in round robin fashion, i.e., first-come,first-serve manner.
However, if we want a thread to relinquish control to another thread to equal priority before its turn comes, we can do so by using the yield() method.
Running State
------------------
Running means that the processor has given its time to the thread for its execution.
1. It has been suspended using suspend() method. A suspend thread cab be revived by using the resume() method.
2. It has been made to sleep. We can put a thread to sleep for a specified time period using the method sleep(time) where time is in milliseconds.
3. It has been wait until some events occurs. This is done using the wait() method. The thread can be scheduled to run again using the notify() method.
Blocked State
------------------
A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state. This happens when the thread is suspended, sleeping, or waiting in order to satisfy certain requirements. A blocked thread is considered "not runnable" but not dead and therefore fully qualified to run again.
Dead State
--------------
Every thread has a life cycle. A running thread ends its life when it has completed executing its run() method. It is natural death.
class ThreadDemo
{
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println("Current Thread="+t);
t.setName("My Thread");
System.out.println("After name change:"+t);
try
{
for(int n=1;n<=5;n++)
{
System.out.println(n);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Main Thread Interrupted");
}
}
}
===================================
class NewThread extends Thread
{
NewThread()
{
start();
}
public void run()
{
try
{
for(int i=1;i<=5;i++)
{
System.out.println("Child Thread:"+i);
Thread.sleep(500);
}
}
catch(InterruptedException ie)
{
System.out.println(ie);
}
}
}
class ThreadExt
{
public static void main(String args[])
{
NewThread nt=new NewThread();
try
{
for(int j=1;j<=5;j++)
{
System.out.println("Main Thread:"+j);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
----------------
Thread Priorities
------------------
To set a thread's priority, use the setPriority() method.
syntax:
final void setPriority(int level)
level
--------
MIN_PRIORITY=1
NORM_PRIORITY=5
MAX_PRIORITY=10
class ThreadPriority
{
public static void main(String args[])
{
A a=new A();
B b=new B();
C c=new C();
a.setPriority(Thread.MIN_PRIORITY);
b.setPriority(Thread.NORM_PRIORITY);
c.setPriority(Thread.MAX_PRIORITY);
System.out.println("Start thread A");
a.start();
System.out.println("Start thread B");
b.start();
System.out.println("Start thread C");
c.start();
System.out.println("End of main thread");
}
}
class A extends Thread
{
public void run()
{
Thread m=Thread.currentThread();
System.out.println("Current Thread"+m);
for(int i=1;i<=5;i++)
{
System.out.println("Thread A:"+i);
}
System.out.println("Exit from Thread A");
}
}
class B extends Thread
{
public void run()
{
Thread n=Thread.currentThread();
System.out.println("current Thread:"+n);
for(int j=1;j<=5;j++)
{
System.out.println("thread B :"+j);
}
System.out.println("Exit form Thread B");
}
}
class C extends Thread
{
public void run()
{
Thread p=Thread.currentThread();
System.out.println("Current Thread :"+p);
for(int k=1;k<=5;k++)
{
System.out.println("Thread C:"+k);
}
System.out.println("Exit from thread c");
}
}
--------------------------------------
class callme
{
String msg;
void call(String m)
{
msg=m;
System.out.println("["+msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class caller implements Runnable
{
String msg;
callme target;
Thread t;
caller(callme targ,String m)
{
msg=m;
target=targ;
t=new Thread(this);
t.start();
}
public void run()
{
synchronized(target)
{
target.call(msg);
}
}
}
class Synchronize
{
public static void main(String args[])
{
callme target=new callme();
caller c1=new caller(target,"hello");
caller c2=new caller(target,"synchronized");
caller c3=new caller(target,"world");
System.out.println(c1.t.isAlive());
System.out.println(c2.t.isAlive());
System.out.println(c3.t.isAlive());
try
{
c1.t.join();
c2.t.join();
c3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println(c1.t.isAlive());
System.out.println(c2.t.isAlive());
System.out.println(c3.t.isAlive());
}
}
--------------------------------------------
class A extends Thread
{
public void run()
{
try
{
for(int i=0;i<5;i++)
{
Thread.sleep(1000);
System.out.println("First Thread");
}
}
catch(InterruptedException ie)
{
System.out.println("Thread Interrupted");
}
}
}
class B extends Thread
{
public void run()
{
try
{
for(int i=0;i<5;i++)
{
Thread.sleep(2000);
System.out.println("Second Thread");
}
}
catch(InterruptedException ie)
{
System.out.println("Thread Interrupted");
}
}
}
class Joins
{
public static void main(String args[])
{
A a1=new A();
a1.start();
try
{
a1.join();
System.out.println("End of First Thread");
}
catch(Exception e)
{
System.out.println("Thread Interrupted");
}
B b1=new B();
b1.start();
try
{
b1.join();
System.out.println("End of Second Thread");
}
catch(Exception e)
{
System.out.println("Thread Interrupted");
}
}
}
================
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
//<applet code=app14 width=250 height=250></applet>
public class app14 extends Applet implements ActionListener,Runnable
{
Label l=null;
Button b1;
Thread t;
boolean a;
Font f=new Font("TimesNewRoman",Font.BOLD,25);
int flag;
public void init()
{
t=new Thread(this);
a=false;
flag=0;
l=new Label("Welcome");
l.setFont(f);
setLayout(null);
l.setBounds(10,20,300,30);
l.setBackground(Color.blue);
l.setForeground(Color.white);
b1=new Button("Stop");
b1.setBounds(130,70,50,30);
b1.addActionListener(this);
add(l);
add(b1);
t.start();
}
public void run()
{
try
{
while(true)
{
int x=(l.getAlignment()==Label.RIGHT)?Label.LEFT:Label.RIGHT;
l.setAlignment(x);
t.sleep(500);
}
}catch(InterruptedException e)
{}
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()=="Start")
{
t.resume();
b1.setLabel("Stop");
}
if(e.getActionCommand()=="Stop")
{
b1.setLabel("Start");
t.suspend();
}
}
}
No comments:
Post a Comment