Programming Tutorials

Java program to print prime numbers using Thread

By: Paawan Chaudhary in Java Tutorials on 2012-09-19  

This is a Java program to implement two threads such that one thread prints prime numbers from 1 to 10 and other thread prints non-prime numbers from 1 to 10 (use Thread class ).
Note :- Each thread has a delay of 500 millsecond after printing one number

import java.lang.*;
import java.io.*;
import java.util.*;
class Prime extends Thread
{
	public void run()
	{
		try
		{
			for(int i=1;i<=10;i++)
			{
				if(i==2||i==3||i==5||i==7)
				{
					System.out.println ("Prime No.= "+i);
				}
				Thread.sleep(500);
			}
		}
		catch (Exception e){}
	}
}
class notPrime extends Thread
{
	public void run()
	{
		try
		{
			for(int i=1;i<=10;i++)
			{
				if(i==4||i==6||i==8||i==9||i==10)
				{
					System.out.println ("Non-Prime No.= "+i);
				}
				Thread.sleep(500);
			}
		}
		catch (Exception e){}
	}
}
class q13Thread
{
	public static void main(String args[])
	{
		new Prime().start();
		new notPrime().start();
	}
}	





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)