Home Java Beginners Java - Threads in Java


Share on Google+Share on Google+

Java - Threads in Java

In this section, you will learn how to use the threads in java.

Java - Threads in Java


Thread is the feature of mostly languages including Java. Threads allow the program to perform multiple tasks simultaneously. Process speed can be increased by using threads because the thread can stop or suspend a specific running process and start or resume the suspended processes. Multitasking or multiprogramming is delivered through the running of multiple threads concurrently. If your computer does not have multi-processors then the multi-threads really do not run concurrently.

This example illustrates how to create a thread and how to implement the thread. In this example we will see that the program prints numbers from 1 to 10 line by line after 5 seconds which has been declared in the sleep function of the thread class. Sleep function contains the sleeping time in millisecond and in this program sleep function has contained 5000 millisecond mean 5 second time. There is sleep function must caught by the InterruptedException. So, this program used the InterruptedException which tells something the user if thread is failed or interrupted.

Here is the code of the program : 

public class Threads{
 public static void main(String[] args){
  Thread th =
 new Thread();
  System.out.println("Numbers are printing line by line after 5 seconds : ");
  for(int i = 1;i <= 10;i++)
  catch(InterruptedException e){
  System.out.println("Thread interrupted!");

Download this example.


If you enjoyed this post then why not add us on Google+? Add us to your Circles

Liked it!  Share this Tutorial

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 7, 2007

Related Tutorials

Ask Questions?    Discuss: Java - Threads in Java   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
Preeti Yadav
April 9, 2011
core java

How i can make a little game in java?
April 11, 2011

Threads in java
June 18, 2011

very nise
Shaukat Ali Shahee
June 27, 2011

Very nice !!!
June 29, 2011

learning core java
July 29, 2011

how to run this program in eclipse,,as i have installed this eclipse in ubuntu,.do i have to add any package name???whn i stared debuging this program it gave 4 errors and i warning..by default what we give package name???/is it necessary that everytime v have to give package name?????
August 26, 2011
Don't use Threads

I have heard a lot of talk about java being a mulithreaded application. The reality is that this is not the case. If you create a java swing application and start a thread with sleep, then the whole application is locked up until that thread starts. I can only think that this is because java is a class driven application and since you invariably will call a thread from within another class instance this is part of one and the same application! Rather schedule stuff in windows task scheduler than scheduling it within the application as this will certainly lock up the application until the thread starts!
August 31, 2011
java thread

its use full for java beginners...
September 5, 2011

September 13, 2011
threads in java

your providing materials realted to thread is too good. i need more examples on multiple threads in java
September 19, 2011
could u tell me ans for this program

Write a multi-threaded Java program to print all numbers below 100,000 that are both prime and fibonacci number (some examples are 2, 3, 5, 13, etc.). Design a thread that generates prime numbers below 100,000 and writes them into a pipe. Design another thread that generates fibonacci numbers and writes them to another pipe. The main thread should read both the pipes to identify numbers common to both.
Vinil Mehta
October 2, 2011
running Example

i couldnt understand why did this example runs as we didnt implement runnable now inherit thread class.?what is this thread th= new Thread()????
November 11, 2011

what is theard in java
January 3, 2012

above example public class Threads extends Thread
January 9, 2012

it is very helpful to us... thnx..:)
Sneha C.Shirke
January 13, 2012

good site..thanku so much
Sneha C.Shirke
January 13, 2012

good site..thanku so much
January 23, 2012
java program related

hiiiiiiiiiii i m inspired from this website. but i want to say something about this that you should improve program because more program have more error ..... using this new user will more satisfy Ramnarayan.......
santoshanand lathkar
February 3, 2012
java notes

best site i have ever vigited
Bonie Jay Manatad
February 6, 2012

How does thread used in gaming programs?
February 7, 2012

Super information
Ram chandra Bhakar
March 14, 2012

this is a good example
March 16, 2012
Correction in the above code

hi , u are wrong with the sleep method. sleep(arg) is a static method of Thread class. u should not call it via thread class object
prashant singh
March 31, 2012

nice thought and have got some special knowledge
May 25, 2012
produer consumer

package ps; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.Map.Entry; class CubbyHole { private int contents; private boolean available = false; File testFile = new File("C:\\test.txt"); ArrayList<Notifications> nofListMain= new ArrayList<Notifications>(); public synchronized int get() throws FileNotFoundException { while (available == false) { try { wait(); } catch (InterruptedException e) { } } readFromFile(); available = false; notifyAll(); return contents; } private void readFromFile() throws FileNotFoundException { try { // File f = new File("laww_protected_list.txt"); BufferedReader br = new BufferedReader(new FileReader(testFile) ); String line = ""; int count = 0; line=br.readLine(); String arrNot [] = new String [4]; while (line != null){ System.out.println(line); if (line != null) { count++; int i=0; StringTokenizer st = new StringTokenizer(line, ","); while(st.hasMoreTokens()){ arrNot[i]=st.nextToken(); i++; } } if(arrNot[3].equalsIgnoreCase("false")){ assignProcessor(arrNot); } line=br.readLine(); } } catch (Exception e) { e.printStackTrace(); } } private void assignProcessor(String[] arrNot) { String prio= arrNot[1]; Integer pr=new Integer(prio); TreeMap<Integer,String []> tMap=new TreeMap<Integer,String []>(); tMap.put(pr,arrNot); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } Entry<Integer, String[]> entry= tMap.pollLastEntry(); entry.getValue(); Processors processor= new Processors(); processor.process(arrNot, nofListMain); } public synchronized void put(Notifications nfObj, ArrayList<Notifications> notList) throws IOException { // while (available == true) { /*try { wait(); } catch (InterruptedException e) { } }*/ //contents = value; writeIntoFile(nfObj, notList); available = true; notifyAll(); } private void writeIntoFile(Notifications contents, ArrayList<Notifications> notList) throws IOException { if (testFile == null) { throw new IllegalArgumentException("File should not be null."); } /*if (!testFile.exists()) { throw new FileNotFoundException ("File does not exist: " + testFile); }*/ if (!testFile.isFile()) { throw new IllegalArgumentException("Should not be a directory: " + testFile); } if (!testFile.canWrite()) { throw new IllegalArgumentException("File cannot be written: " + testFile); } nofListMain= notList; //use buffering Writer output = new BufferedWriter(new FileWriter(testFile, true)); //FileWriter always assumes default encoding is OK! try { if(contents!=null){ output.write( contents.getName()+","+contents.getPriority()+","+contents.getWork()+","+contents.isProcessed+"\n"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { output.close(); } } }
July 3, 2012
Discuses Java

Good programing example give me
July 18, 2012

threats in java
August 5, 2012
new improvement

i looking every tutorial about java in this site.i have a problem about .its may b new idea.sml thing.bcx i decide to say every examples after the given there avnswr.its easy to understand.
August 17, 2012
error in thread example

when i run the thread show error class ir imterface r excepted
zahid hussain
October 22, 2012

e.printStackTrace(); my means it has what kind of function
November 28, 2012
Creating a fan using threads

Someone tolled me to visit your page and he said i wont regret
himanshu mishra
November 27, 2013
java threads

when interrupted exception occur in java threads ?
ambika pratap
January 21, 2014

jdbc aur database connectivity kishe hota hai sir
June 30, 2014
threads in java

plsss send all by using thread programes code
suresh kumar
August 23, 2012

all coding send my mail address