Wednesday, June 24, 2009

How to Determine When a Thread Has Finished


// Create and start a thread
Thread thread = new SampleThread();
thread.start();

if (thread.isAlive()) {
// Thread is still running
} else {
// Thread is finished
}

How to Stop a Thread


There are two methods(stop() and suspend()) available in Thread class to stop the thread. As these methods are deprecated, it is advisable not to use these methods and use below mentioned approach to stop the thread.

// Create and start the thread
SampleThread thread = new SampleThread();
thread.start();
//...Some Code...
// Stop the thread
thread.done = true;

class SampleThread extends Thread {
boolean done = false;
// This method is called when the thread runs
public void run() {
while (true) {
// ...Some Code...
if (done) {
return;
}
// ...Some Code...
}
}
}

How to Create a Thread


There are two ways to create a thread.
1) Using Thread class
2) Using Runnable interface

Using Thread class:

// This class extends Thread
class SampleThread extends Thread {
// This method is the entry point of thread. It is called when thread runs.
public void run() {
}
}

// Create and start the thread
Thread thread = new SampleThread();
thread.start();


Using Runnable interface:

class SampleThread implements Runnable {
// This method is called when the thread runs
public void run() {
}
}

// Create the object with the run() method
Runnable runnable = new SampleThread();

Thread thread = new Thread(runnable);

// Start the thread
thread.start();

How to Execute a Command


try {
// Execute a command. "ls -a" a unix command. So, this command will work on unix only.
String command = "ls -a";
Process child = Runtime.getRuntime().exec(command);

} catch (IOException e) {

}

How to List All System Properties


// Get all system properties
Properties props = System.getProperties();

// Enumerate all system properties
Enumeration enum = props.propertyNames();
for (; enum.hasMoreElements(); ) {
// Get property name
String propName = (String)enum.nextElement();

// Get property value
String propValue = (String)props.get(propName);
}

How to Get and Set the Value of a System Property


// Get a system property
String dir = System.getProperty("SampleProperty");

// Set a system property
String previousValue = System.setProperty("SampleProperty", "newValue");

Tuesday, June 23, 2009

How to Convert a Primitive Type Value to a String


// Use String.valueOf()
String s = String.valueOf(true); // true
s = String.valueOf('a'); // a
s = String.valueOf((short)111); // 111
s = String.valueOf(111); // 111
s = String.valueOf(111L); // 111
s = String.valueOf(1.11F); // 1.11
s = String.valueOf(1.11D); // 1.11
 

Sample Java Codes Copyright © 2008 Green Scrapbook Diary Designed by SimplyWP | Made free by Scrapbooking Software | Bloggerized by Ipiet Notez