Skip to content

Instantly share code, notes, and snippets.

@resetter
Last active February 9, 2016 17:02
Show Gist options
  • Save resetter/27fa06e9f08d74e437f4 to your computer and use it in GitHub Desktop.
Save resetter/27fa06e9f08d74e437f4 to your computer and use it in GitHub Desktop.
Program to find time difference in calculating 100,000 prime numbers single and multithreaded
class ThreadTest
{
public static void main(String [] args)
{
MyThread t1 = new MyThread(0);
MyThread t2 = new MyThread(0);
System.out.println("Time difference calculating 100000 prime numbers, single/multithreaded:");
long start_time = System.nanoTime();
t1.run();
t2.run();
long end_time = System.nanoTime();
double difference = (end_time - start_time)/1e9;
double roundOff = Math.round(difference * 100.00) / 100.00;
System.out.println("Simultaneous duration: "+roundOff+" seconds");
start_time = System.nanoTime();
t1.run();
t1.interrupt();
t2.run();
t2.interrupt();
end_time = System.nanoTime();
difference = (end_time - start_time)/1e9;
roundOff = Math.round(difference * 100.00) / 100.00;
System.out.println("Series duration: "+roundOff+" seconds");
}
}
class MyThread extends Thread
{
private int startpoint, status = 1, num = 3;
public MyThread(int s)
{
this.startpoint = s;
}
@Override
public void run()
{
{
for ( int count = startpoint; count <= 100000; )
{
for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
{
if ( num%j == 0 )
{
status = 0;
break;
}
}
if ( status != 0 )
{
// System.out.println(num);
count++;
}
status = 1;
num++;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment