0

I'm very new to "threading" and don't know how to use it. I did use to create a new Thread for every test case, and those threads were never terminated. Single keyword search is also working fine for me but things get messed up when I create a new keyword every time for a new thread.

Junit Test:

public class Test{

    @Test
    public static void someTest() {

        SSH ssh = new SSH();

        // test logic
        String key = "some_value from test logic";

        ssh.start(key);
    }
}

The SSH Thread:

public class SSH extends Thread {
    String key = "";

    public void run {
        ssh(key);
    }

    public SSH(String key) {
        this.key = key;
    }


    public static void ssh(String key) {
        // some logic
    }

}
fuggerjaki61
  • 822
  • 1
  • 11
  • 24
john
  • 1
  • 1

1 Answers1

0

At first a Thread is for executing code while other code will run on. It is like you say one person should count from 0 to 100 and another person should say the ABC. This is not possible without threads.


Reading a live log file is a problem that can be solved with threads.

Using a thread that looks like this:

public class SSHThread extends Thread {

    private String key;
    private volatile boolean endFlag;

    public SSHThread(String key) {
        this.key = key;
    }
    // stops thread from executing
    public void stop() {
        endFlag = true;
    }

    @Override
    public void run() {
        // pre logic

        while (true) {    // runs infinitely
            if (endFlag) {
                break;

                // could also be 'return;' if there is no 'post logic'
            }

            ssh(key);
        }

        // post logic
    }
}

This thread runs forever until the programm is stopped so it is a good idea to call stop() before exiting the programm. This thread should do everthing you need.

Maybe if you need it, set endFlag to true or call stop() in ssh().


Some lecture

What is a "thread" (really)?

Java read a logfile live

How to properly stop the Thread in Java?

Threads in Java

What does 'synchronized' mean?

What is the volatile keyword useful for

Avoid Deadlock example

fuggerjaki61
  • 822
  • 1
  • 11
  • 24