2 Questions How to use join() and Which is best coding pratice.
Hi All,
I have 2 Question:
I have a MultipleThread class and when I try to use join method of thread class I get compile time error(so i commented it out).I also wanted to know is the best approch to write a threaded program.I also wanted to know about the best coding pratice for threadand also do I need to declare Instance variable thread and name(Is it possible to create multiple thread with out declaring instance variable thread and name , if yes which one is the better way 1> with instance variable 2> with out instance variable)
Sorry here is the code.
package javaProg.completeReferance;
public class MultipleThread implements Runnable
{
Thread thread;
String name;
MultipleThread(String nam)
{
this.name=nam;
thread = new Thread(this,name);
thread.start();
}
public void run()
{
try
{
for (int i=1;i<=10;i++ )
{
Thread.sleep(1000);
System.out.println("Thread "+name+" "+i);
}
}
catch (InterruptedException e)
{
System.out.println(""+e);
}
}
public static void main(String [] args)
{
try
{
MultipleThread t1=new MultipleThread("One");
MultipleThread t2=new MultipleThread("Two");
MultipleThread t3 =new MultipleThread("Three");
//t1.join();
//t2.join();
//t3.join();
for (int i=1;i<=10;i++ )
{
Thread.sleep(1000);
System.out.println("Parent Thread "+i);
}
}
catch (InterruptedException e)
{
System.out.println(" "+e);
}
}
}
import java.util.*;
public class PrintTask implements Runnable{
private int sleepTime;
private String threadName;
private Random generator = new Random();
public PrintTask(String name) {
threadName = name;
sleepTime = generator.nextInt(5000);
}
public void run() {
try {
System.out.printf("%s going to sleep for %d seconds.\n", threadName, sleepTime);
Thread.sleep(sleepTime);
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.printf("%s done sleeping\n", threadName);
}
}
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
public class RunnableTester
{
public static void main( String[] args )
{
// create and name each runnable
PrintTask task1 = new PrintTask( "thread1" );
PrintTask task2 = new PrintTask( "thread2" );
PrintTask task3 = new PrintTask( "thread3" );
System.out.println( "Starting threads" );
// create ExecutorService to manage threads
ExecutorService threadExecutor = Executors.newCachedThreadPool();
// start threads and place in runnable state
threadExecutor.execute( task1 );
threadExecutor.execute( task2 );
threadExecutor.execute( task3 );
threadExecutor.shutdown();
System.out.println( "Threads started, main ends\n" );
}
}