Hi Guys ,
Today I want to discuss about Thread class some important points . Every Fresher in Java should understand this basic concepts . These are fundamental things in Thread .
Thread is basically Small piece of code would executing separately . Normally Thread used to solve the business logic without obstructing the present scenario .Normally OS are two types . Single Tasking and multi tasking . here what is single tasking we need to understand . So here each task will be executed sequentially .even though you requested for multiple tasks . this is performance related issue . Hence Multi Threaded environment has been invented to solve this kind of business logic. In multi threaded environment all the tasks will be started immediately but there will be switching 2mechanism implemented by OS . which is not visible we feel like all the tasking are running at time . But internally It happens based on switching mechanism .
When comes to Language threads . These threads are tied up with OS threads when you start Threads. Normally In java We two ways are there to start threads .
1) Implements Runnable
2) Extends Thread . But here Thread class implements Runnable .
Read the below book which is very easy to understand
Thread class Basics
*******************
1) Once Thread is dead you can not start Thread again . It will give illegal state exception
2) Once thread object is created . It will not be in Live state until unless you start that .
3) Runnable , Run are the thread states JVM will switch threads to different states .
4) Blocked /Suspended are states in which thread will move based on wait() and sleep method
Thread class has following methods
----------------------------------
Yield() - static method
sleep() - static method - will not release locks
start() - normal method
join() -normal method
Runnable Interface Methods
***************************
run() is only method from this interface
Object class Methods
*********************
wait() - will release locks , should be called in synchronized block
notify() - should be called in synchronized block
notifyAll() - should be called under synchronized block
wait() - will release locks immediately .
notify() - will not release locks immediately until unless it comes out of synchronized block
Means as soon as Notify() called if the Other thread which executing synchrionized block will not release that lock unless it comes out of that block. So the thread which is acquiring lock has to wait till that time
Wait () - will cause current thread to release locks and moves to Blocked state
notify() - Notify one thread that is waiting for lock on that Object
notifyAll() - notifyAll threads those are waiting for lock on that Object pool
join() - current thread will join end of the calling thread
yeild() - will pause present thread execution and encourages Same priority Thread to be executed
Some of the Thread Programs done By me
***********************************************
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mythreadtest;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author root
*/
public class Operator extends Thread {
long x=0;
long y=0;
long radius=0;
public void run() {
System.out.println("Opreator Thread has started");
while (true) {
synchronized (this) {
//calculate machine steps
x=(int)Math.ceil(Math.random()*100);
y=(int)Math.ceil(Math.random()*100);
radius=(int)Math.ceil(Math.random()*100);
Hardware.x=(int)x;
Hardware.y=(int)y;
Hardware.radius=(int)radius;
notify();
}
}
}
}
Machine and Hardware Program Thread
***********************************
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mythreadtest;
import java.awt.Frame;
import java.awt.Graphics;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author root
*/
public class Hardware extends Frame implements Runnable {
static int x=0;
static int y = 0;
static int radius = 0;
private Operator operator;
public Hardware()
{
setVisible(true);
setTitle("hardware");
setSize(300,300);
}
public void paint(Graphics g)
{
g.drawOval(x,y, radius,radius);
for(int i=x;i>=0;i--)
g.drawOval(i,y, radius,radius);
}
public void run()
{
System.out.println("Hardware Thread Started");
while(true)
{
try {
synchronized (operator) {
try {
operator.wait();
} catch (InterruptedException ie) {
}
System.out.println("Hw X:--->" + x);
System.out.println("Hw Y:--->" + y);
System.out.println("Hw Rad:--->" + radius);
}
Thread.sleep(2000);
repaint();
} catch (InterruptedException ex) {
Logger.getLogger(Hardware.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* @return the operator
*/
public Operator getOperator() {
return operator;
}
/**
* @param operator the operator to set
*/
public void setOperator(Operator operator) {
this.operator = operator;
}
public static void main(String args[])
{
Operator or= new Operator();
Hardware hr=new Hardware();
hr.setOperator(or);
or.start();
Thread thr=new Thread(hr);
thr.start();
synchronized(or)
{
try {
or.wait();
} catch (InterruptedException ex) {
Logger.getLogger(Operator.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Reader - writer problem
************************
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mythreadtest;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author root
*/
public class Reader extends Thread {
Calculator c;
public Reader(Calculator c)
{
this.c=c;
}
public void run()
{
while(true)
{
synchronized(c)
{
try {
c.wait();
} catch (InterruptedException ex) {
Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println(c.total);
}
}
public static void main(String args[])
{
Calculator c=new Calculator();
Reader r1=new Reader(c);
Reader r2=new Reader(c);
Reader r3=new Reader(c);
r1.start();
r2.start();
r3.start();
c.start();
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mythreadtest;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author root
*/
public class Writer extends Thread {
public void run()
{
while(true)
{
notifyAll();
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mythreadtest;
/**
*
* @author root
*/
public class Calculator extends Thread {
int total = 0;
public void run() {
synchronized (this) {
for (int i = 0; i <= 99; i++) {
total += i;
}
notifyAll();
}
}
}
Circle generation Program Using Threads
***************************************
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mythreadtest;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author root
*/
public class ThreadA extends Frame implements Runnable, ActionListener,MouseListener,MouseMotionListener,WindowListener {
int x=0;
int y=0;
int radius=0;
public ThreadA()
{
setVisible(true);
setTitle("My Thread");
setSize(300,300);
addMouseListener(this);
addMouseMotionListener(this);
addWindowListener(this);
}
public static void main(String args[])
{
new ThreadA();
}
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void paint(Graphics g)
{
for(int i=y;i>0;i--){
DrawThread dr=new DrawThread();
dr.start();
synchronized(dr)
{
try {
System.out.println("Waiting for DR to complete");
dr.wait();
} catch (InterruptedException ex) {
Logger.getLogger(ThreadA.class.getName()).log(Level.SEVERE, null, ex);
}
}
g.drawOval(x, i, radius, radius);
}
System.out.println("Paint Is Called");
g.drawString(x+":"+":"+radius, x, y);
}
public void mouseClicked(MouseEvent e) {
ThreadB b=new ThreadB();
b.start();
synchronized(b)
{
try{
System.out.println("Waiting for B to complete...");
b.wait();
}catch(InterruptedException ee)
{
ee.printStackTrace();
}
System.out.println("x:---->"+b.x);
System.out.println("y:---->"+b.y);
System.out.println("rad:---->"+b.radius);
x=(int)b.x;
y=(int)b.y;
radius=(int)b.radius;
repaint();
}
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
System.exit(1);
}
public void windowClosed(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
public void run() {
repaint();
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mythreadtest;
/**
*
* @author root
*/
public class ThreadB extends Thread {
long radius ;
long x;
long y;
public void run()
{
synchronized(this)
{
x=(long)Math.ceil(Math.random()*100);
y=(long)Math.ceil(Math.random()*100);
radius=(long)Math.ceil(Math.random()*100);
System.out.println(Math.random());
notify();
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mythreadtest;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author root
*/
public class DrawThread extends Thread {
public DrawThread()
{
}
public void run()
{
synchronized(this)
{
try {
sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(DrawThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
I hope you enjoyed this technical discussion
pls give comments
|
Comments