Simple Thread using extending Thread and implementing Runnable
Multi-threading means a single code program with different parts executed at same time in parallel, those parts are threads. We here see how to create threads.Class 1: The first class SimpleThreadTest here instantiate a common printer, which receives input strings from multiple threads and prints. And creates two threads for different thread classes Thread1 and Thread2. And starts them both. By running this class you will see the output console with Threads names in mixed order ie., the thread executes parallel with one another same time.
public class SimpleThreadTest {public static void main(String[] args) {
MyPrinter p = new MyPrinter();
Thread1 t1= new Thread1(p);
Thread2 t2= new Thread2(p);
t1.start();
t2.start();
}
}
Class 2: This is the Thread implementation which does some calculation and send the data to be printed to common printer class. The common printer instance is given here as constructor argument.
public class Thread1 extends Thread {private MyPrinter printer;
Thread1(MyPrinter printer) {
this.printer = printer;
}
public void run(){
int i=0;
while( i < 200 ) {
printer.print("Thread 1", i);
i++;
}
}
}
Class 3: This is the (Thread2) Thread implementation which does some calculation and send the data to be printed to common printer class. The common printer instance is given here as constructor argument.
public class Thread2 extends Thread {private MyPrinter printer;
Thread2(MyPrinter printer) {
this.printer = printer;
}
public void run(){
int i=0;
while( i < 200 ) {
printer.print("Thread 2", i);
i++;
}
}
}
Class 4: This is a common printer class has public method print called from different thread instances. Prints the thread name and data(i).
public class MyPrinter {public void print(String pName,int i)
{
System.out.println(pName+"_"+i);
}
}
No comments:
Post a Comment