Threads
To make something able to execute as a separate thread, that is concurrently
with the rest of the program (the Java Virtual Machine uses timesharing
to support threads), make a new class that extends Thread. It
must have a constructor which is used to give the thread its initial
data (perhaps a socket that it is to talk on), and a method void run()
which specifies what the thread does when it executes.
Construct a new object
of that type, and call its void start() method, and it will run. You must
not redefine start() it is inherited from Thread, and is responsible for
creating the actual Thread structures then calling the run method that you
did define. Example implementing a concurrent internet server
import java.io.*;
import java.net.*;
public class Server extends Thread
{ Socket sock;
public Server(Socket s)
{ sock=s; }
public void run()
{ try
{ InputStream issock=sock.getInputStream();
OutputStream ossock=sock.getOutputStream();
InputStreamReader isrsock=new InputStreamReader(issock);
BufferedReader in=new BufferedReader(isrsock);
PrintWriter out=new PrintWriter(ossock,true);
while (true)
{ String s=in.readLine();
if (s==null) break;
out.println("You sent \""+s+"\""); }
sock.close(); }
catch (Exception e)
{ System.out.println("Failure: "+e.getMessage()); } } }
....
....
try
{ ServerSocket ssock=new ServerSocket(3456);
while (true)
{ Socket temp=ssock.accept();
Server agent=new Server(temp);
agent.start(); } }
catch (Exception e)
{ System.out.println("Failure: "+e.getMessage()); }
A client to work with this example would follow this form:
try
{ Socket sock=new Socket("www.bumbly.com",3456);
InputStream issock=sock.getInputStream();
OutputStream ossock=sock.getOutputStream();
InputStreamReader isrsock=new InputStreamReader(issock);
BufferedReader in=new BufferedReader(isrsock);
PrintWriter out=new PrintWriter(ossock,true);
out.println("hello");
System.out.println("I sent \"hello\"");
String s=in.readLine();
System.out.println("and got back \""+s+"\"");
out.println("good bye");
System.out.println("I sent \"good bye\"");
s=in.readLine();
System.out.println("and got back \""+s+"\"");
sock.close(); }
catch (Exception e)
{ System.out.println("Failure: "+e.getMessage()); }