我如何使用多个线程作为客户端 - 谁都在switch语句中执行任务

时间:2018-05-07 10:48:48

标签: java multithreading arraylist switch-statement client-server

如何使用多个线程作为客户端 - 谁都在switch语句中执行任务?我还希望线程执行这些任务,一旦它们执行完就停止(目前这些任务是从用户输入执行的)。

服务器,客户端和开发人员数据库共有3个类,它们包含服务器中ArrayList中“开发人员”对象的构造函数。此数组列表提供了根据特定请求传递给客户端的信息。

这是我的代码:客户:

 import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.*;

public class QuoteOfTheDayClient_2 {
static String devName;
static String devSkill;
static Boolean devHire;
static Socket echoSocket = null;  // holds the Socket object
static Scanner fromServer = null;   // input stream from remote host
static Scanner fromServer1 = null;   // input stream from remote host
static PrintWriter toServer = null; // output stream to remote host
static PrintWriter toServer1 = null; // output stream to remote host
static Scanner stdIn = new Scanner(System.in);
static String remoteServer = "localhost";          // are you 'local'?!
//String remoteServer = "193.61.190.96"; // remote host is not 'local'!
static int port;
static String reply;// holds reply from remote host


  public static void searchForSkill(String skill) {
    toServer.println(1);
    String quoteNum = "php"; //Search for a specific coding language - 
  Specific to the entered parameters
    System.out.println("Searching for Skill: " + skill + " in Developer 
   Database");
    toServer.println(quoteNum);
    while (!(reply = fromServer.nextLine()).isEmpty()) {
        // System.out.println(reply1);
        System.out.println(reply);// print reply to screen
    }
    fromServer.nextLine();     // Consume the newline
    System.out.println();

   }
   public static void addDeveloper(String name, String skill,boolean 
   hire) 
    {
    toServer.println(2);
    System.out.println("Add Developer to system ");
    stdIn.nextLine();   // flush newline
    String quoteString = name;//stdIn.nextLine();
    String quoteString1 = skill;//stdIn.nextLine();
    boolean quoteString2 = hire;//stdIn.nextLine();
    toServer.println(quoteString);
    toServer.println(quoteString1);
    toServer.println(quoteString2);
    fromServer.next();
    System.out.println("\nDeveloper entered: " + quoteString + "\n");
    while (!(reply = fromServer.nextLine()).isEmpty()) {
        // System.out.println(reply1);
        System.out.println(reply);// print reply to screen
    }
 }
 public static void checkAvailability(String developerName) {
    try {
        toServer.println(3);
        System.out.println("Send Developer Name to Find Availability: 
       ");
        String quoteDel = developerName;
        toServer.println(quoteDel);
        while (!(reply = fromServer.nextLine()).isEmpty()) {
            // System.out.println(reply1);
            System.out.println(reply);// print reply to screen
        }
    } catch (NoSuchElementException e) {
    }
   }

  public static void hireDeveloper(String name) {
    toServer.println(4);
    String quoteNum = name; //Search for a specific coding language - 
   Specific to the entered parameters
    System.out.println("Searching for: " + name + " in Developer 
   Database");
    toServer.println(quoteNum);
    while (!(reply = fromServer.nextLine()).isEmpty()) {
        // System.out.println(reply1);
        System.out.println(reply);// print reply to screen
    }
    fromServer.nextLine();     // Consume the newline
    System.out.println();

  }

  public static void printAllDevelopers(){
    toServer.println(5);
    while (!(reply = fromServer.nextLine()).isEmpty()) {
        // System.out.println(reply1);
        System.out.println(reply);// print reply to screen
    }
    fromServer.nextLine();     // Consume the newline
    System.out.println();

  }

    public static void clientMenu(){

    try {
        port = 4444; // 17 for localhost
        echoSocket = new Socket(remoteServer, port);
        fromServer = new Scanner(echoSocket.getInputStream());
        fromServer1 = new Scanner(echoSocket.getInputStream());
        toServer = new PrintWriter(echoSocket.getOutputStream(), true);
        toServer1 = new PrintWriter(echoSocket.getOutputStream(), 
     true);
        OutputStream os = echoSocket.getOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(os);


    } catch (Exception e) {
        System.err.println("Exception: " + e);
        System.exit(1);
    } // try-catch

    String reply;// holds reply from remote host
    int command;
    String reply1;
    String devName="David Blaine";
    String devSkill="Java";

    System.out.println("Enter command: 1:Search Skill    2:Add 
  Developer   3:Search Availability    4:Hire Developer    5:Show all 
  Developers   6:Exit");

    command = 0;
    command = command+1;

   // while (command != 0) {
  for(int i=1;i<6;i++) {
  command=i;
  switch (i) {
    case 1: {
        // get quote
        searchForSkill("PHP");
        break;
    }
    case 2: {
        // add quote
        addDeveloper("David Blaine", "Java", true);
        break;
    }
    case 3: {
        // delete quote
        checkAvailability("David Ferguson");
        break;
    }
    case 4: {
        hireDeveloper("Thompson");
        break;
    }
    case 5: {
        printAllDevelopers();
    }
    case 6: {
        System.exit(6);
    }
    default:
        System.out.println("*** Command not recognised ***");
        break;
}
System.out.println("Enter command: 1:Search Skill    2:Add Developer   
3:Search Availability    4:Hire Developer    5:Show all Developers   
6:Exit");
command = stdIn.nextInt();
//}
}
toServer.println(command);
try {
    echoSocket.close();
} catch (IOException e) {
    e.printStackTrace();
}
fromServer.close();
toServer.close();
stdIn.close();

}
public static void main(String[] args) throws IOException {
 clientMenu();







 } // main
 } // EchoClient

服务器代码:

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;

public class QuoteOfTheDayServer_2 {
    private static DeveloperDatabase[] developerList = new 
DeveloperDatabase[7];
    static DeveloperDatabase temp []=new DeveloperDatabase[7];

    static String userAddDevName;
    static String userAddCodeSkills;
    static Boolean userAddHireAvailability;
    static int command;

    static List<DeveloperDatabase> list = new 
 ArrayList<DeveloperDatabase>(){

        {
            add(new DeveloperDatabase(1,"David Ferguson", "Java", 
 true));
            add(new DeveloperDatabase(2,"Grant Thompson", "Java", 
 true));
            add(new DeveloperDatabase(3,"Craig Jackson", "C++", true));
            add(new DeveloperDatabase(4,"Kevin James","C++", true));
            add(new DeveloperDatabase(5,"Greg Troupe", "Python", 
 true));
            add(new DeveloperDatabase(6,"James Smith", "Python", 
 true));
            add(new DeveloperDatabase(7,"Jamie Richie", "PHP", true));
            add(new DeveloperDatabase(8,"Rory McGrattan", "PHP", 
 false));
        }

    };

    public static String printJava(){
        String message="";
        for (int i=0;i<2;i++){
            message +=list.get(i).toString();
            message+=" \n";

        }
        return message;
    }
    public static String printC(){
        String message="";
        for (int i=2;i<4;i++){
            message +=list.get(i).toString();
            message+=" \n";

        }
        return message;
    }
    public static String printPy(){
        String message="";
        for (int i=4;i<6;i++){
            message +=list.get(i).toString();
            message+=" \n";

        }
        return message;
    }
    public static String printPHP(){
        String message="";
        for (int i=6;i<8;i++){
            message +=list.get(i).toString();
            message+=" \n";

        }
        return message;
    }

    public static void addDeveloper(String name,String 
codeSkill,Boolean hire){
        userAddDevName=name;
        userAddCodeSkills = codeSkill;
        userAddHireAvailability = hire;
        System.out.println("*********Adding Developer***********");
        System.out.println(userAddDevName+ " has been added to the 
system");
        list.add(new DeveloperDatabase(9, 
userAddDevName,userAddCodeSkills, userAddHireAvailability));
        System.out.println(list.get(8));
    }//addDeveloper

    public static String checkAvail(String clientMessage){
        String message="";
        for (int i=0;i<list.size();i++){
            if 
(clientMessage.equalsIgnoreCase(list.get(i).getDeveloperName())) {
                message+= list.get(i).toString();
                message+="\n";
            }
        } return message;
    }
    public static String printAllDevelopers(){
        String message="";
        for (int i=0;i<8;i++){
            message +=list.get(i).toString();
            message+=" \n";

        }
        return message;
    }





    public static void main(String[] args) throws IOException {




        // Wrap the standard System.in stream with a Scanner so that
        Scanner stdIn = new Scanner(System.in);
        Scanner fromClient = null;
        PrintWriter toClient = null;
        PrintWriter toClient1=null;

        int pNum = 4444;
        ServerSocket sSocket = null;
        Socket cSocket = null;

        try {
            sSocket = new ServerSocket(pNum);
        } catch (IOException e) {
            System.out.println("Couldn't listen on port: " + pNum + "; 
" + 
    e);
            System.exit(1);
        }

        // Continuously wait for client; accept them; and send a quote 
to 
    them.
        while (true) {
            try {
                System.out.println("Waiting for client ....");
                // Blocking 'accept' i.e. wait for a client
                cSocket = sSocket.accept();
                System.out.println("Client connected from: " + 
    cSocket.getInetAddress());

                // Set up the output stream for the server, i.e. a 
    PrintWriter stream
                toClient = new PrintWriter(cSocket.getOutputStream(), 
    true);
                toClient1 = new PrintWriter(cSocket.getOutputStream(), 
    true);

                ObjectInputStream ois = new 
     ObjectInputStream(cSocket.getInputStream());
                fromClient = new Scanner(cSocket.getInputStream());
                try {
                    command = fromClient.nextInt();
                    //fromClient.nextLine();
                } catch (InputMismatchException e){
                    System.out.print("Your selection can only be an 
     integer!");
                }

                System.out.println("Received command: " + command + " 
 from 
     client at " + cSocket.getInetAddress());

                while (command != 0) {
                    switch (command) {
                        case 1: // get skills
                        {
                            System.out.println("GET skill");
                            fromClient.nextLine();
                            String quoteNum = 
     fromClient.nextLine();//receive from client
                            if (quoteNum.equalsIgnoreCase("Java")) {
                                toClient1.println(printJava());
                            } else if 
 (quoteNum.equalsIgnoreCase("C++")) {
                                toClient1.println(printC());
                            } else if 
 (quoteNum.equalsIgnoreCase("Python")) 
    {
                                toClient.println(printPy());
                            } else if 
  (quoteNum.equalsIgnoreCase("PHP")) {
                                toClient.println(printPHP());
                            }
                            else {
                                toClient.println("No developer with 
  those 
    skills found");
                            }
                            // 
    toClient.println(list.equals("Java"));//number -1 for array (0) to 
    client print
                            System.out.println("Pushed Developer 
  number: " 
    + quoteNum + " to client at " + cSocket.getInetAddress());
                            //toClient.println(quotes[quoteNum]); // 
  return 
    quote          //if "java' { get(0)   get(1)
                            break;
                        }
                        case 2: // add quote
                        {
                            System.out.println("ADD Developer to 
  System");
                            fromClient.nextLine();   // flush newline
                            String quote = fromClient.next();
                            fromClient.nextLine();
                            String quote1 = fromClient.next();
                            fromClient.nextLine();
                            boolean quote2 = fromClient.nextBoolean();

  toClient.println("The\t*************Developer 
    has been Added to the Developer Database********");
                            list.add(new DeveloperDatabase(9, quote, 
    quote1, quote2));
                            toClient.println(list.get(8).toString());
                            //addDeveloper(quote,quote1,quote2);
                            System.out.println(list.get(8));
                            //System.out.println("Received quote from 
    client:" + quote);
                            quote = quote + "\n\n";
                            //list.add((quote);
                            System.out.println("Added Developer: " + 
    quote);
                            break;
                        }
                        case 3: // Check if Developer is available
                        {
                            System.out.println("Check if developer is 
    Available\n");
                            fromClient.nextLine();
                            String quoteNum = fromClient.nextLine();
                            System.out.println("Checking availability 
  for: 
    " + quoteNum);
                            if (quoteNum.equalsIgnoreCase("Rory 
    McGrattan")) {
                                toClient.println("The Developer is not 
    available for hire");
                            } else {
                                toClient.println("The Developer is 
    available for hire");
                            }break;
                        }case 4: {
                            System.out.println("Hire A Developer");
                            String quoteNum =fromClient.next();
                            System.out.println("Client wants to hire: 
    "+quoteNum);
                            String message = quoteNum;
                            for(int i=0;i<list.size();i++){
                            if 
    (quoteNum.equalsIgnoreCase(list.get(i).getDeveloperName())){
                                    list.get(i).hireDeveloper();
                                }//if
                            }//if
                            //System.out.println(message);
                            toClient.println("******* You have Hired: 
 "+ 
     message+" ********");
                            break;
                        }
                        case 5: {// Print all Developers
                            String message="";
                            for (int i=0;i<8;i++){
                                message +=list.get(i).toString();
                                message+=" \n";
                            }
                            toClient.println(message);
                        }
                        default:
                                break;

            }
            try {
                //command = fromClient.nextInt();
            }catch(InputMismatchException e){
            }
                    System.out.println("Received command: " + command + 
    "from client at " + cSocket.getInetAddress());
                }
                // Close all streams
                toClient.close();
                cSocket.close();
                fromClient.close();
                stdIn.close();
            } catch (IOException e) {
                System.out.println("Accept failed: " + pNum + "; " + 
 e);
                System.exit(1);
            }
        }
    } // main
    } // QuoteOfTheDayServer_2

DeveloperDatabase代码:

public class DeveloperDatabase {
private  int id;
private  String developerName;
private  String codingLanguage;
private  boolean freeForHire;

public  DeveloperDatabase(){

}

public  DeveloperDatabase(int id,String name,String codeSkills,boolean 
hire){
    this.id = id;
    this.developerName = name;
    this.codingLanguage=codeSkills;
    this.freeForHire=hire;
}


public String toString() {
    String message = "\tName: " +developerName;
    message += "\n" + "\tCoding Language:  "+ codingLanguage+"\n";

    if (freeForHire== true) {
        message += "\tThe developer is Available! for Hire!\n";
    } else {
        message += "\tThe developer is not Available for Hire!\n";
    }

    return message;
}//toString


public boolean getFreeForHire() {

    if (freeForHire==true){
        System.out.println("The Developer is free to hire!");
    }else{
        System.out.println("The Developer is not free to hire!");
    }
    return freeForHire;

 }

public  String getCodingLanguage() {
    return codingLanguage;
 }

public void hireDeveloper(){
    if (freeForHire==true)
        freeForHire = false;
        System.out.println(developerName +" is Hired!");
    }

public String getDeveloperName() {
    return developerName;
}

public static void main(String[] args) {

}//main
}//class   

1 个答案:

答案 0 :(得分:0)

你可以用类似的东西 //将执行者服务定义为具有5个线程

1)

ExecutorService service=Executors.newFixedThreadPool(5);

2) //将(在命令!= 0)中移动代码insde替换为实现runnable的单独类,让我们调用此任务。

public class Task实现了Runnable {

private final Integer command;

public  Task(Integer command) {
    this.command=command;
}
@Override
public void run() {
    //do something, like switch statement 

}

}

3)创建一个辅助方法,并调用此方法

public void process(Task t){
        service.submit(t);
    }