Home | Add to Favorites | Ebooks Directory | News  
Java Programming
Home
Java  Article
Java Tutorial 
Java download
Books
JDBC
Java Training
Java Source  Code
Java Applet
Java Questions
Java MultiThreading Sample Program

The following Program explains  about Multithreading in java with simple program


 

/*
* Multithreading.java
*
* Created on May 1, 2005, 12:17 PM
*/

/**
*
* @author Administrator
*/
import java.util.*;

public class Multithreading {

/** Creates a new instance of Multithreading */
public Multithreading() {
}
public static void main(String a[]){
Queue q=new Queue();
ThreadWriter thread1=new ThreadWriter(q);
ThreadReader thread2=new ThreadReader(q);
Thread reader=new Thread(thread1);
Thread writer=new Thread(thread2);

writer.start();
reader.start();
}
}

class ThreadReader implements Runnable{
Queue q;
ThreadReader(Queue q){
this.q=q;
}
public void run(){
while(true){
q.getData();
}
}
}
class ThreadWriter implements Runnable{
Queue q;
ThreadWriter(Queue q){
this.q=q;
}
public void run(){
int i=0;
try{
while(true){
q.putData("string "+i);
i++;
Thread.sleep(100);
}}
catch(InterruptedException e){

}
}
}
class Queue{

Vector vtrData=new Vector();
public synchronized void getData(){
if(vtrData.size()==0){
try{
wait();
}
catch(Exception e){
e.printStackTrace();
}
}
else{
System.out.println("data removed");
vtrData.remove(0);
}
}
public synchronized void putData(String data){
vtrData.add(data);
System.out.println("data added");
notifyAll();
}

}



 
This is a simple Java program explains about multithreading

Visit Java Article part to find more java programs