Skip to content

Instantly share code, notes, and snippets.

@surabhisuman
Created April 2, 2023 12:55
Show Gist options
  • Save surabhisuman/54265bbc0aaa029f014e33aa2c9d49b1 to your computer and use it in GitHub Desktop.
Save surabhisuman/54265bbc0aaa029f014e33aa2c9d49b1 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
public class PrimeNumbers {
private static class MultiThreadPrimeNumber implements Runnable {
private int finish;
private int start;
public MultiThreadPrimeNumber(int start, int finish) {
this.start = start;
this.finish = finish;
}
private void getPrime() {
List<Integer> prime = new ArrayList<>();
for (int num = start; num <= finish; num ++) {
boolean isPrime = true;
for (int j = 2; j <= num/2; j++) {
if (num % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
prime.add(num);
}
}
System.out.println("\n Prime numbers in " + start + " - " + finish + " region are "+ prime);
}
@Override
public void run() {
System.out.println("Thread is executing " + Thread.currentThread().getName());
getPrime();
}
}
public static void main(String[] args) {
int start = 1;
int finish = 10;
List<Thread> threads = new ArrayList<>();
for (int i = 1; i <= 10; i++ ) {
String threadName = i + "th thread";
Thread thread = new Thread(new MultiThreadPrimeNumber(start, finish), threadName);
threads.add(thread);
start += 10;
finish += 10;
}
for (Thread thread : threads) { thread.start(); }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment