Good evening, I got this two programs here
httpServer.java
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicInteger;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class httpServer extends Thread {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/test", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
AtomicInteger atomicInteger = new AtomicInteger(0);
int theValue = atomicInteger.get();
@Override
public void handle(final HttpExchange t) throws IOException {
final String response;
final String requestMethod = t.getRequestMethod();
if ("GET".equals(requestMethod)) {
response = String.format("Besuche: %d%n", atomicInteger.addAndGet(1));
}
else if ("POST".equals(requestMethod)) {
atomicInteger.set(0);
response = "Reset to 0";
}
else {
throw new IOException("Unsupported method");
}
t.sendResponseHeaders(200, response.length());
final OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
Test.java
public class Test {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Now i want that the Test.java to start working when i start the httpServer.java. I want to achieve this with threads. I found this here online which expalins how i make a thread but i dont know how to get the Test.java to work there.
Note: I know i could write both in one programm but i want to know how to work with threads for another project im working on.
To start a thread you need to implement the run
-Method. Everything inside the run
-Method will be executed in a new Thread.
You did not implement a run method so the call of server.start();
does acutally nothing. With a run
-Method it would look like this:
public class httpServer extends Thread
{
//Everything inside this method is executed in a new Thread
@Override
public void run()
{
super.run();
System.out.println("THIS IS EXECUTED IN A THREAD");
this.serverStuff();
}
private void serverStuff()
{
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/test", new MyHandler());
server.setExecutor(null); // creates a default executor
}
}
public class Test
{
public static void main(String[] args)
{
System.out.println("THIS IN NOT EXECUTED IN THREAD");
//This call creates a new Thread. It calls the run()-Method
new httpServer().start();
}
}
This might be useful ! But i think @Kayaman already provided an answer !
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.