我目前正在研究一個基於多線程的基於Java的程序,它應該允許多個線程向該程序發送請求。這應該與事件激活一起處理,但我很難理解事件及其實現。下面是允許多個線程與程序進行通信的代碼,但我只有一個線程。有人可以提供更多的信息嗎?非常感激。如何在Java中創建事件
//this is a a threads class
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Niti implements Runnable {
public String line;
public Socket soc;
public boolean active=true;
public Niti(Socket soc)
{
this.soc=soc;
this.line=line;
this.active=active;
}
public synchronized void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(soc.getInputStream()));
line=br.readLine();
while(line!=null && !line.equals("")){
if(!this.active)
break;
System.out.println(line);
line=br.readLine();
}
BufferedOutputStream bos = new BufferedOutputStream(soc.getOutputStream());
bos.write("Poruka iz Programa".getBytes());
}
catch (IOException ex) {
Logger.getLogger(Niti.class.getName()).log(Level.SEVERE, null, ex);
}
try {
soc.close();
} catch (IOException ex) {
Logger.getLogger(Niti.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
//and this is the main class
public class Server{
public static synchronized void main(String[] args) throws IOException, InterruptedException{
ServerSocket ss = new ServerSocket(1000);
while(true){
Socket sokit = ss.accept();
Niti n = new Niti(sokit);
while(true){
Thread t = new Thread(n);
t.start();
//Thread.sleep(4000);
//n.active=false;
System.out.println("nit broj:" + Thread.currentThread().getId());
}
}
}
}
對不起,但我很難理解你在問什麼。你想傳遞一些參數給新的線程嗎? – m0skit0 2013-04-11 18:39:59
嗨伊凡,我注意到你在相同的方法中兩次捕獲相同的'IOException'。儘管這沒有什麼區別,但最好對同一個「IOException」使用1個catch塊。這會使你的代碼更整潔一些。 – blackpanther 2013-04-11 18:47:00
我想要做的是使多個線程訪問此服務器,而不是一個。如果你把這段代碼放到你的Net Beans中,它將只通過一個線程循環。最後我被告知,爲了讓多個線程能夠訪問服務器,我需要創建一些事件和偵聽器,以幫助解決此問題。我不知道如何做到這一點,你有什麼想法,我應該從哪裏開始? TY – 2013-04-11 18:50:29