如何在java中实现线程

时间:2016-12-15 15:59:47

标签: java multithreading

我创建了一个移动运营商,它向服务器发送号码,我添加了一个线程,但它一直显示0,我需要做什么来增加我的线程,就像>第一次>线程 - 0,第二次> THread-1等。就像img IMG一样 我的代码:

package PPC4;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Random;
public class Client extends Thread {
    Client() {
      // The compiler creates the byte code equivalent of super ();
    }
    Client(String name) {
        super (name); // Pass name to Thread superclass
    }
    public static Socket socket;

    public void run() {
        Random randomGenerator = new Random();
        String host = "localhost";
        int port = 25000;
        try {            
            InetAddress address = InetAddress.getByName(host);
            socket = new Socket(address, port);
             //Send the message to the server

            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);

            int randomInt = randomGenerator.nextInt(999999);
            String number = "069"+randomInt;
            String sendMessage = (number+1) + "\n";
            bw.write(sendMessage);
            bw.flush();
            System.out.println("The telephone number sent to the server: "+sendMessage);

            System.out.println ("The following user connected : " + getName ());
            //Get the return message from the server
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String message = br.readLine();
            System.out.print(" " +message);
        } catch(Exception exception) {
            exception.printStackTrace();
        }
    }

    public static void main(String args[]) {
        {
            Client mt;
            if (args.length == 0)
                mt = new Client ();
            else
                mt = new Client(args[0]);
            mt.start ();
       }
    }
}

1 个答案:

答案 0 :(得分:1)

如果您没有将任何参数传递给您的代码,它将默认创建名为Thread-0的线程。如果你传递至少一个参数,它将创建一个名称与该参数相等的线程。