'how to calculate as many primes as we can in ten seconds using threads in java
I just started java and I am trying to learn java as much as possible. I was trying to solve a problem but couldn't get the right solution. I have tried this program according to my own logic, ended in failure. Looking forwards for someone's guidence.
public class ThreadDemo implements Runnable
{
Thread t;
ThreadDemo()
{
t=new Thread(this,"Child");
t.start();
}
public void run()
{
try
{
Thread.sleep(2000);
}
catch (Exception ex){}
}
public static void main(String[] args)
{
ThreadDemo td=new ThreadDemo();
Thread t1=Thread.currentThread();
t1.setName("prime");
try
{
for(int i=0;;i++)
{
if(i!=0&&i!=1&& i%i ==1 && i%2!=0)
{
Thread.sleep(1);
System.out.println(i + "j");
}
}
}
catch (Exception ex){}
}
}
Solution 1:[1]
I think you are trying to learn to use threads by implementing a function that calculate primies in 10 senconds. In other words, you want to stop the prime number calculation after 10 seconds by multithreading. So you could set a flag in the prime calculation loop to make it stop, and then in another thread make it change after 10 seconds.
By the way, your way of calculating prime numbers is incorrect. I show you the core that printing numbers as many as posible in 10 senconds. You can modify the code to print prime numbers?
public class ThreadDemo implements Runnable {
Thread t;
static boolean flag = true;
ThreadDemo() {
t = new Thread(this, "Child");
t.start();
}
public void run() {
try {
Thread.sleep(10_000);
flag = false;
} catch (Exception ex) {
}
}
public static void main(String[] args) {
ThreadDemo td = new ThreadDemo();
Thread t1 = Thread.currentThread();
t1.setName("prime");
try {
for (int i = 0; flag; i++) {
System.out.println(i);
Thread.sleep(1);
}
} catch (Exception ex) {
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ryoii |
