I have a class, that needs to generate from time to time, a key and share it with a client and a server.
Kdc Class:
protected Kdc() {
(do stuff)
runKdc();
}
private void runKdc(){
for(;;){
generateKey();
informClients();
informServers();
try {
Thread.sleep(generationTime);
} catch (InterruptedException e) {
System.out.println("Sleep Interrupted");
}
}
}
Main class:
public static void main(String[] args) {
Kdc kdc = new Kdc();
System.out.println("done"); //Doesn't reach the line
}
Now my problem is that i need to do something after starting the Kdc class and i can't! Because of the infinite loop, it just gets stuck in the Main class, after starting the Kdc class. Any ideas?
Thank you.
You should run your KDC in a sperate thread. This thread will run in the background, and your main method will proceed.
And for this loop:
while(true){
//do something
}
is much better than your for(;;){} loop. Replace the "true" by a boolean variable like "running" or "active"
As other have said you should create the Kdc in it's own thread, for example
package com.testingarea;
class Kdc {
public Kdc() {
runKdc();
}
private void runKdc() {
while(true) {
System.out.println("Running kdc");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class RunKdc implements Runnable {
@Override
public void run() {
Kdc k = new Kdc();
}
}
public class TestThread {
public static void main(String[] args) {
new Thread(new RunKdc()).start();
System.out.println("Kdc thread started");
}
}
Start the Kdc class in a new Thread, or creat a timer for executing kdc.runKdc()
. You can creat the instance in the new thread like in the example below, or only run the code of runKdc()
in a new thread.
public static void main(String[] args)
{
Thread keyGenerationThread= new Thread()
{
@Override
public void run()
{
Kdc kdc = new Kdc();
}
};
keyGenerationThread.start();
System.out.println("done");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.