Java starting two threads? [duplicate]

<div class="question-status question-originals-of-duplicate">

This question already has an answer here:

    <li> What is the difference between Thread.start() and Thread.run()? <span class="question-originals-answer-count"> 9 answers </span> </li> </ul>

    i am new to java. I have two classes that looks like:

    public class hsClient implements Runnable { public void run() { while(true){ } } } public class hsServer implements Runnable { public void run() { while(true){ } } }

    If i try to start both classes as Thread it wont start the second thread. It looks like he stuck in the first one.

    This is my main class:

    public static void main(String[] args) throws IOException { hsClient client = new hsClient(); Thread tClient = new Thread(client); tClient.run(); System.out.println("Start Client"); hsServer server = new hsServer(); Thread tServer = new Thread(server); tServer.run(); System.out.println("Start Server"); }

    If i run my code it only prints "Start Client" but not "Start Server" on the console

    Answer1:

    Replace tClient.run() with tClient.start() and tServer.run() with tServer.start().

    Calling the run method directly executes it in the current thread instead of in a new thread.

    Answer2:

    To start a thread use the start method.

    Thread tClient = new Thread(client); tClient.start(); // start the thread

    More info on threads can be found e.g. in the JavaDoc

    人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:Java starting two threads? [duplicate]