用线程运行java程序

时间:2015-10-28 17:46:21

标签: java multithreading server

晚上好,我在这里得到了这两个节目

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!"); 
}
}

现在我希望Test.java在启动httpServer.java时开始工作。 我想通过线程实现这一点。我在网上找到了这个here,它解释了我如何制作一个帖子,但我不知道如何让Test.java在那里工作。

注意:我知道我可以在一个程序中编写这两个程序但我想知道如何使用线程来处理另一个项目。

2 个答案:

答案 0 :(得分:1)

要启动一个线程,您需要实现run - 方法。 run - Method中的所有内容都将在新的Thread中执行。

您没有实现run方法,因此server.start();的调用实际上没有任何内容。使用run - 方法,它看起来像这样:

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();
    }
}

答案 1 :(得分:0)

This可能有用!但我认为@Kayaman已经提供了答案!