Java 将对象传递到线程(访问线程外的对象)
我正在做一个简单的服务器-客户端系统 服务器启动,创建一个只存储信息的对象,然后在接收到连接后,创建一个运行线程的新对象 对于每个线程,我都希望将第一个对象作为参数传递以修改它(添加/获取信息),但我认为传递它的不是。在我第一次尝试菜单并尝试做一些事情时发现了它 已经看到一些关于这个问题的帖子,但我不知道如何应用到我的代码中 以下是服务器代码:Java 将对象传递到线程(访问线程外的对象),java,multithreading,java-threads,Java,Multithreading,Java Threads,我正在做一个简单的服务器-客户端系统 服务器启动,创建一个只存储信息的对象,然后在接收到连接后,创建一个运行线程的新对象 对于每个线程,我都希望将第一个对象作为参数传递以修改它(添加/获取信息),但我认为传递它的不是。在我第一次尝试菜单并尝试做一些事情时发现了它 已经看到一些关于这个问题的帖子,但我不知道如何应用到我的代码中 以下是服务器代码: import java.io.*; import java.net.*; import java.net.*; public class Servid
import java.io.*;
import java.net.*;
import java.net.*;
public class Servidor {
static final int PORT = 8000;
public static void main(String args[]) {
ServerSocket serverSocket = null;
Socket socket = null;
int i = 0;
//the object that will only store info
WorkLoad wk;
wk = new WorkLoad();
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Leiloes do Ave 2097");
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new thread passing the previously created object
//new WorkLoad(socket, wk).start();
Thread t = new Thread(new WorkLoad(socket, wk));
t.start();
}
}
}
将完成这些工作的类:
import java.net.*;
import java.util.*;
import java.io.*;
import java.lang.*;
public class WorkLoad extends Thread implements Runnable {
protected Socket socket;
//private int y; //usado no menu?
private int clientes;
private int leiloes;
private int tid; //thread id
private HashMap<Integer,Cliente> lClientes; //lista de todos os clientes existentes <ID,Cliente()>
private HashMap<Integer,Leilao> lLeiloes; //lista de todos os leilões existents <ID, Leilao()>
private HashMap<Integer,String> lThreads; //lista das threads
private String[] menu = new String[10];
// the construtor of the object to store info
public WorkLoad() { this.clientes = 0; this.leiloes = 0 ; this.tid = 0;} //fazer sempre ++ ao criar
// and here what i thought would pass the object to the thread, the thread constructor
public WorkLoad(Socket clientSocket, WorkLoad wk) {
this.socket = clientSocket;
//this.tid = id;
//wk.addTid(id,"");
}
public HashMap<Integer,Cliente> getListaClientes() { return this.lClientes; }
public HashMap<Integer,Leilao> getListaLeiloes() { return this.lLeiloes; }
public void addCliente(Integer id, Cliente c) { this.lClientes.put(id,c); }
public void addLeilao(Integer id, Leilao l) { this.lLeiloes.put(id,l); }
public int getTotalLeiloes() { return this.leiloes; }
public int getTotalClientes() { return this.clientes; }
public void addTid(int id,String s) { lThreads.put(id,s); } //adiciona thread lista
public int getTid() { return this.tid; }
public String getTidMsg(int id) { return lThreads.get(id);} //devolve mensagem da lista de threads
public Leilao getLeilao(Integer id) { return this.lLeiloes.get(id); } //devolve o leilao pela id
public void run() {
PrintWriter out = null;
BufferedReader in = null;
DataOutputStream cout = null;
//private HashMap<Integer,String> lThreads;
//MENU
menu[0] = "1"; //menu de escolha menu[0] = MENU.A.APRESENTAR
menu[1] = "- Registo de utilizador - :insere o username e depois a password\n"; //tem de fazer 2 readlines
menu[2] = "- Login de utilizador - :insere o username e depois a password\n"; //tem de fazer 2 readlines
menu[3] = "- Menu geral - :1)Criar Leilao:2)Listar Leiloes:3)Licitar leilao:4)Terminar Leilao:Para sair escreva exit\n";
menu[4] = "- Licitar leilao - :Insere o id de leilao e depois o valor da tua licitação com . (ex 5.5)\n"; //tem de fazer 2 readlines
menu[5] = "- Criar leilao - :Insere a descricao do item\n";
menu[6] = "- Terminar Leilao -:Insere a id do leilao que queres terminar\n";
try {
//System.out.println(socket.getInetAddress() + " entrou.");
//ArrayList<String>
out = new PrintWriter(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//v2
cout = new DataOutputStream(socket.getOutputStream());
cout.writeBytes("Bem vindo ao leilões do Ave :1) Registo :2) login :exit para sair.\n");
String input;
//cria nova instancia de cliente
Cliente clithread = new Cliente(wk.getTotalClientes());
//while((input = in.readLine()) != null) {
while(true) {
input = in.readLine(); //Lê uma linha - tem de se tratar linha a linha
if(input.equals("exit")) { in.close(); cout.close(); socket.close(); return; }
if(input.equals("1")) { } // registo cliente
//cout.writeBytes(menu[input.toString()]); //print menu registo
//input = in.readLine(); //lê username
//cout.writeBytes("Recebi a mensagem:" + input + "\n"); //POR O \n no fim ou o cliente nao funciona direito!!
//System.out.println(input); //print no server local
}
// in.close();
// out.close();
// socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.net.*;
导入java.util.*;
导入java.io.*;
导入java.lang.*;
公共类工作负载扩展线程实现可运行{
保护插座;
//private int y;//usado没有菜单吗?
私人int客户;
莱洛斯私人酒店;
private int tid;//线程id
私有HashMap lClientes;//现有客户列表
私有HashMap lLeiloes;//lista de todos os leilões existents
私有HashMap lThreads;//lista das线程
私有字符串[]菜单=新字符串[10];
//要存储信息的对象的构造函数
公共工作负载(){this.clientes=0;this.leiloes=0;this.tid=0;}//fazer sempre++ao criar
//在这里,我认为应该将对象传递给线程,线程构造函数
公共工作负载(Socket客户端Socket,工作负载工作){
this.socket=clientSocket;
//this.tid=id;
//工作地址(id为“”);
}
公共HashMap getListaClientes(){返回this.lClientes;}
public HashMap getListaLeiloes(){返回this.lLeiloes;}
public void addCliente(整数id,Cliente c){this.lclients.put(id,c);}
public void addLeilao(整数id,Leilao l){this.lleiloos.put(id,l);}
public int getTotalElios(){返回this.leios;}
public int getTotalClient(){返回this.clientes;}
public void addTid(int-id,String s){lThreads.put(id,s);}//adiciona-thread-lista
public int getId(){返回this.tid;}
公共字符串getTidMsg(int-id){return lThreads.get(id);}//devolve mensage da lista de threads
public Leilao getLeilao(整数id){返回this.lleiloos.get(id);}//devolve o Leilao pela id
公开募捐{
PrintWriter out=null;
BufferedReader in=null;
DataOutputStream cout=null;
//私有哈希映射读取;
//菜单
menu[0]=“1”;//menu de escolha menu[0]=menu.A.APRESENTAR
菜单[1]=“Registo de utilizador-:insere o username e depois a password\n”;//tem de fazer 2 readlines
菜单[2]=“-Login de utilizador-:insere o username e depois a password\n”;//tem de fazer 2 readlines
菜单[3]=“-menu geral-:1)Criar Leilao:2)Listar leiloos:3)Licitar Leilao:4)Terminar Leilao:Para sair escreva exit\n”;
菜单[4]=“-Licitar leilao-:插图o id de leilao e deposis o valor da tua licitaço com.(ex 5.5)\n”;//tem de fazer 2阅读行
菜单[5]=“-Criar leilao-:插入描述项\n”;
菜单[6]=“-Terminar Leilao-:插入一个id do Leilao que querys Terminar\n”;
试一试{
//System.out.println(socket.getInetAddress()+“entrou”);
//ArrayList
out=新的PrintWriter(socket.getOutputStream());
in=新的BufferedReader(新的InputStreamReader(socket.getInputStream());
//v2
cout=新的DataOutputStream(socket.getOutputStream());
写操作系统(“Bem vindo ao leilões do Ave:1)注册:2)登录:退出状态。\n”);
字符串输入;
//cria nova instancia de cliente
clienteclienthread=newcliente(wk.getTotalClientes());
//而((input=in.readLine())!=null){
while(true){
input=in.readLine();//Lêuma linha-tem de se tratar linha a linha
if(input.equals(“exit”){in.close();cout.close();socket.close();return;}
if(input.equals(“1”){}//注册客户
//cout.writeBytes(菜单[input.toString()]);//打印菜单注册表
//input=in.readLine();//lêusername
//cout.writeBytes(“Receibi a mensage:“+input+”\n”);//没有fim或客户nao功能指令!!
//System.out.println(输入);//不打印本地服务器
}
//in.close();
//out.close();
//socket.close();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
}
当我试图访问wk.get inther the run()时,我注意到了我的问题,它说它找不到对象。好的……你的代码中有很多东西是可疑的
Workload(Socket socket) {
this.clientes = 0; this.leiloes = 0 ; this.tid = 0;
this.socket = socket;
}
无需创建一个工作负载对象并将其传递给另一个工作负载对象。好的……代码中有很多东西是可疑的
Workload(Socket socket) {
this.clientes = 0; this.leiloes = 0 ; this.tid = 0;
this.socket = socket;
}
无需创建一个工作负载对象并将其传递给另一个工作负载对象。这里有几件事要做 每次获得连接时,您都会创建一个新的工作负载对象。我认为您希望所有的连接共享您在程序开始时创建的工作负载,但实际情况并非如此。
Thread t = new Thread(new Worker(socket, wk));
t.start();