Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create an event in Java
    text
    copied!<p>I am currently working on a multi-threaded socket based Java program that should allow multiple threads to send request to this program. This should be handled with the event activation but I am having hard time understanding events and their implementation. Below is the code that should allow more than 1 thread to communicate with the program but I only have 1 thread there. Can someone please shed more light on this? Much appreciated.</p> <pre><code>//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 &amp;&amp; !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()); } } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload