Sunday, April 1, 2012

Thread - Java


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

Slider

Image Slider By engineerportal.blogspot.in The slide is a linking image  Welcome to Engineer Portal... #htmlcaption

Tamil Short Film Laptaap

Tamil Short Film Laptaap
Laptapp

Labels

About Blogging (1) Advance Data Structure (2) ADVANCED COMPUTER ARCHITECTURE (4) Advanced Database (4) ADVANCED DATABASE TECHNOLOGY (4) ADVANCED JAVA PROGRAMMING (1) ADVANCED OPERATING SYSTEMS (3) ADVANCED OPERATING SYSTEMS LAB (2) Agriculture and Technology (1) Analag and Digital Communication (1) Android (1) Applet (1) ARTIFICIAL INTELLIGENCE (3) aspiration 2020 (3) assignment cse (12) AT (1) AT - key (1) Attacker World (6) Basic Electrical Engineering (1) C (1) C Aptitude (20) C Program (87) C# AND .NET FRAMEWORK (11) C++ (1) Calculator (1) Chemistry (1) Cloud Computing Lab (1) Compiler Design (8) Computer Graphics Lab (31) COMPUTER GRAPHICS LABORATORY (1) COMPUTER GRAPHICS Theory (1) COMPUTER NETWORKS (3) computer organisation and architecture (1) Course Plan (2) Cricket (1) cryptography and network security (3) CS 810 (2) cse syllabus (29) Cyberoam (1) Data Mining Techniques (5) Data structures (3) DATA WAREHOUSING AND DATA MINING (4) DATABASE MANAGEMENT SYSTEMS (8) DBMS Lab (11) Design and Analysis Algorithm CS 41 (1) Design and Management of Computer Networks (2) Development in Transportation (1) Digital Principles and System Design (1) Digital Signal Processing (15) DISCRETE MATHEMATICS (1) dos box (1) Download (1) ebooks (11) electronic circuits and electron devices (1) Embedded Software Development (4) Embedded systems lab (4) Embedded systems theory (1) Engineer Portal (1) ENGINEERING ECONOMICS AND FINANCIAL ACCOUNTING (5) ENGINEERING PHYSICS (1) english lab (7) Entertainment (1) Facebook (2) fact (31) FUNDAMENTALS OF COMPUTING AND PROGRAMMING (3) Gate (3) General (3) gitlab (1) Global warming (1) GRAPH THEORY (1) Grid Computing (11) hacking (4) HIGH SPEED NETWORKS (1) Horizon (1) III year (1) INFORMATION SECURITY (1) Installation (1) INTELLECTUAL PROPERTY RIGHTS (IPR) (1) Internal Test (13) internet programming lab (20) IPL (1) Java (38) java lab (1) Java Programs (28) jdbc (1) jsp (1) KNOWLEDGE MANAGEMENT (1) lab syllabus (4) MATHEMATICS (3) Mechanical Engineering (1) Microprocessor and Microcontroller (1) Microprocessor and Microcontroller lab (11) migration (1) Mini Projects (1) MOBILE AND PERVASIVE COMPUTING (15) MOBILE COMPUTING (1) Multicore Architecute (1) MULTICORE PROGRAMMING (2) Multiprocessor Programming (2) NANOTECHNOLOGY (1) NATURAL LANGUAGE PROCESSING (1) NETWORK PROGRAMMING AND MANAGEMENT (1) NETWORKPROGNMGMNT (1) networks lab (16) News (14) Nova (1) NUMERICAL METHODS (2) Object Oriented Programming (1) ooad lab (6) ooad theory (9) OPEN SOURCE LAB (22) openGL (10) Openstack (1) Operating System CS45 (2) operating systems lab (20) other (4) parallel computing (1) parallel processing (1) PARALLEL PROGRAMMING (1) Parallel Programming Paradigms (4) Perl (1) Placement (3) Placement - Interview Questions (64) PRINCIPLES OF COMMUNICATION (1) PROBABILITY AND QUEUING THEORY (3) PROGRAMMING PARADIGMS (1) Python (3) Question Bank (1) question of the day (8) Question Paper (13) Question Paper and Answer Key (3) Railway Airport and Harbor (1) REAL TIME SYSTEMS (1) RESOURCE MANAGEMENT TECHNIQUES (1) results (3) semester 4 (5) semester 5 (1) Semester 6 (5) SERVICE ORIENTED ARCHITECTURE (1) Skill Test (1) software (1) Software Engineering (4) SOFTWARE TESTING (1) Structural Analysis (1) syllabus (34) SYSTEM SOFTWARE (1) system software lab (2) SYSTEMS MODELING AND SIMULATION (1) Tansat (2) Tansat 2011 (1) Tansat 2013 (1) TCP/IP DESIGN AND IMPLEMENTATION (1) TECHNICAL ENGLISH (7) Technology and National Security (1) Theory of Computation (3) Thought for the Day (1) Timetable (4) tips (4) Topic Notes (7) tot (1) TOTAL QUALITY MANAGEMENT (4) tutorial (8) Ubuntu LTS 12.04 (1) Unit Wise Notes (1) University Question Paper (1) UNIX INTERNALS (1) UNIX Lab (21) USER INTERFACE DESIGN (3) VIDEO TUTORIALS (1) Virtual Instrumentation Lab (1) Visual Programming (2) Web Technology (11) WIRELESS NETWORKS (1)

LinkWithin