Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
1.40/5 (3 votes)
See more:
HOW TO IMPLEMENT THREADS IN JAVA CODE
Posted
Updated 6-Jun-14 2:36am
Comments
[no name] 6-Jun-14 8:50am    
By screaming at them?

Threads in java can be implemented in two ways.
1. By inheriting the Thread class.
2. By implementing Runnable Interface.

Inherting Thread Class


Java
// ThreadDemo.java
class ThreadDemo
{
   public static void main (String [] args)
   {
      MyThread mt = new MyThread ();
      mt.start ();
      for (int i = 0; i < 50; i++)
           System.out.println ("i = " + i + ", i * i = " + i * i);
   }
}
class MyThread extends Thread
{
   public void run ()
   {
      for (int count = 1, row = 1; row < 20; row++, count++)
      {
           for (int i = 0; i < count; i++)
                System.out.print ('*');
           System.out.print ('\n');
      }
   }
}


Implementing Runnable Interface
Java
package com.myjava.threads;
 
class MyRunnableThread implements Runnable{
 
    public static int myCount = 0;
    public MyRunnableThread(){
         
    }
    public void run() {
        while(MyRunnableThread.myCount <= 10){
            try{
                System.out.println("Expl Thread: "+(++MyRunnableThread.myCount));
                Thread.sleep(100);
            } catch (InterruptedException iex) {
                System.out.println("Exception in thread: "+iex.getMessage());
            }
        }
    } 
}
public class RunMyThread {
    public static void main(String a[]){
        System.out.println("Starting Main Thread...");
        MyRunnableThread mrt = new MyRunnableThread();
        Thread t = new Thread(mrt);
        t.start();
        while(MyRunnableThread.myCount <= 10){
            try{
                System.out.println("Main Thread: "+(++MyRunnableThread.myCount));
                Thread.sleep(100);
            } catch (InterruptedException iex){
                System.out.println("Exception in main thread: "+iex.getMessage());
            }
        }
        System.out.println("End of Main Thread...");
    }
}


best luck

 
Share this answer
 
By understanding[^] them.
 
Share this answer
 
Generally speaking, you have two choices to implement a thread:
1) Write a subclass of java.lang.Thread;

Java
class YouClass extends Thread
{
   public void run(){
      //Your execution code goes here  
   }

}


2) Implement java.lang.Runnable interface.

Java
class YourClass implements Runnable
{
    public void run(){
      //Your execution code goes here  
   }
}
 
Share this answer
 
It's very easy:
Thread t = new Thread(new Runnable(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
			
		}
    	  
      });
      t.start();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900