Saturday, June 9, 2007
Commanding Threads in Java
Following are source to command threads in java
Command.java
package tekzgeek.thread;
public class Command
{
public static int PAUSE=0;
public static int RESUME=1;
public static int EXIT=2;
int state=RESUME;
int command=RESUME;
synchronized public int getCommand()
{
if(this.state==this.command)
return this.state;
if((this.state==RESUME)&&(this.command==PAUSE))
{
this.state=PAUSE;
notify();
while((this.command!=Command.RESUME)&&(this.command!=Command.EXIT))
{
try
{
wait();
}
catch(InterruptedException e)
{}
}
if(this.command==Command.RESUME)
this.state=Command.RESUME;
else if(this.command==Command.EXIT)
this.state=Command.EXIT;
}
else if((this.state==Command.RESUME)&&(this.command==Command.EXIT))
{
this.state=Command.EXIT;
notify();
}
return this.state;
}
synchronized public void setCommand(int command_temp)
{
this.command=command_temp;
if(state==command)
return;
if((this.state==Command.RESUME)&&(this.command==Command.PAUSE))
{
while(this.state!=Command.PAUSE)
{
try
{
wait();
}
catch(InterruptedException e)
{}
}
}
else if((state==PAUSE)&&(command==RESUME))
{
notify();
}
else if((this.state==Command.RESUME)&&(this.command==Command.EXIT))
{
while(this.state!=Command.EXIT)
{
try
{
wait();
}
catch(InterruptedException e)
{}
}
}
else if((this.state==Command.PAUSE)&&(this.command==Command.EXIT))
{
notify();
}
}
}
WorkerThread.java
package tekzgeek.thread;
import tekzgeek.thread.Command;
public class WorkerThread extends Thread
{
Command command;
public WorkerThread(Command command)
{
this.command=command;
}
public void run()
{
boolean EXIT=false;
while(!EXIT)
{
// Do Some Work
System.out.println("Worker Thread Running.");
try
{
Thread.sleep(200);
}catch(InterruptedException e)
{}
int cmd=command.getCommand();
if(cmd==Command.EXIT)
EXIT=true;
}
System.out.println("I am done.");
}
}
Main.java
package tekzgeek.thread;
import tekzgeek.thread.Command;
import tekzgeek.thread.WorkerThread;
public class Main
{
public static void main(String args[])throws InterruptedException
{
Command command=new Command();
WorkerThread workerThread=new WorkerThread(command);
workerThread.start();
Thread.sleep(1000);
System.out.println("Main Thread is trying to Pause Worker Thread.");
command.setCommand(Command.PAUSE);
System.out.println("Main Thread Paused Worker Thread.");
Thread.sleep(1000);
System.out.println("Main Thread is trying to Resume Worker Thread.");
command.setCommand(Command.RESUME);
System.out.println("Main Thread Resumed Worker Thread.");
Thread.sleep(1000);
System.out.println("Main Thread is trying to Stop Worker Thread.");
command.setCommand(Command.EXIT);
System.out.println("Main Thread stopped Worker Thread.");
}
}
Command.java- The basic core for transfering messages between threads.
Main.java- Main Thread that commands Worker Thread.
WorkerThread.java- This thread does the work and is controlled by Main Thread.
pl note : One way command is only implemented. To go for two way communication or for feedback,create
one more command for getting feedback from worker thread.
Configure Log4j/ Log4j Example
Steps to configure Log4j and to run a simple application are
1. Download Log4j from http://www.apache.org/
2. Extract all the contents to a directory.
3. In the directory find the jar file log4j-X.X.XX.jar under directory \dist\lib. Make sure ur class path points to this jar file.
4. Create a file named Log4jDemo.java and put the following contents in it.
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class Log4jDemo
{
static Logger logger = Logger.getLogger(Log4jDemo.class);
public static void main(String args[])
{
PropertyConfigurator.configure("log4j.properties"); // or u can use file name with path eg. D:\\Demo\\log4j.properties
logger.debug("DEBUG Message");
logger.info("INFO Message");
logger.warn("WARN Message");
logger.error("ERROR Message");
logger.fatal("FATAL Message");
}
}
5. Create a new file named log4j.properties at the same directory where u have put the Log4jDemo.class file. Put the following contents in to it.
log4j.rootLogger=DEBUG, MF ,CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.CONSOLE.layout.ConversionPattern=[%t] %C at %L %-5p %c %x - %m%n
log4j.appender.MF=org.apache.log4j.RollingFileAppender
log4j.appender.MF.File=Main.log
log4j.appender.MF.MaxFileSize=100KB
# Keep one backup file
log4j.appender.MF.MaxBackupIndex=1
log4j.appender.MF.layout=org.apache.log4j.PatternLayout
log4j.appender.MF.layout.ConversionPattern=[%t] %C at %L %-5p %F (%L) %c %x - %m%n
6.Now when u run the Log4jDemo.java u get a console ouput and also saved to a file called Main.log
Writing a Content to a file in Java
import java.io.*;
public class FileWriterDemo
{
public static void main(String args[]) throws FileNotFoundException,IOException
{
File file=new File("Demo.txt"); // or u can use file name with path eg. D:\\Demo\\Demo.txt
if(!file.exists())
file.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(file,true));// true flag tells us to append to the exiting file.
out.write("Hello World.");
out.newLine();
out.close();
}
}
Save above contents in a file called FileWriterDemo.java
Reading a Content of a file in java
import java.io.*;
public class FileReaderDemo
{
public static void main(String args[]) throws FileNotFoundException,IOException
{
File file1=new File("Demo.txt"); // or u can use file name with path eg. D:\\Demo\\Demo.txt
BufferedReader in = new BufferedReader(new FileReader(file1));
String str;
while ((str = in.readLine()) != null) {
System.out.print(str);
}
in.close();
}
}
Save above contents in a file called FileReaderDemo.java
Sunday, May 20, 2007
Subscribe to:
Posts (Atom)