Credits

Friday, January 22, 2010

Java's Thread

Java makes use of Thread to allow multi-tasking or programming. Threads can be created either through extending the Thread class or implementing Runnnable interface.


The program below shows a simple use of a Thread. It shall display  n number  "This is a sample one." and another n number of  of " This is a sample two."  With multi-threading, there is no precise pattern as to the output since OS will determine the resources including time to which activity shall be done first and for how long.  Thus, multiple runs of this program may produce different results. 





[+/-] show/hide




class SampleThread1 extends Thread
{
public void run()
{
  for(int x=1;x<=25;x++) System.out.println("This is a sample one!"); }}  

class SampleThread2 extends Thread
{
public void run()
{
  for(int x=1;x<=25;x++) System.out.println("This is a sample two!"); }}  
class SentenceThread {
public void main(String[] args) {
SampleThread1 myFirst= new SampleThread1();
SampleThread2 mySecond= new SampleThread2();
myFirst.start();
mySecond.start();}}  

AddThis