...
Code Block | ||
---|---|---|
| ||
class StopSocket implements Runnable { private final Socket socket; private final BufferedReader in; private final Object lock = new Object(); private volatile boolean done = false; public StopSocket() throws IOException { this.socket = new Socket("somehost", 25); this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); } private final Object lock = new Object(); // Only one thread can use the socket at a particular time public void run() { String string; try { synchronized (this.lock) { while (!this.done && (string = this.in.readLine()) != null) { // Blocks until end of stream (null) } } } catch (IOException ie) { // Forward to handler } } public void shutdown() { this.done = true; } public static void main(String[] args) throws IOException, InterruptedException { StopSocket ss = new StopSocket(); Thread thread = new Thread(ss); thread.start(); Thread.sleep(1000); ss.shutdown(); } } |
...
Code Block | ||
---|---|---|
| ||
class StopSocket implements Runnable { // ... public void run() { String string; try { synchronized (this.lock) { while (!Thread.interrupted() && (string = this.in.readLine()) != null) { // Blocks until end of stream (null) } } } catch (IOException ie) { // Forward to handler } } public static void main(String[] args) throws IOException, InterruptedException { StopSocket ss = new StopSocket(); Thread thread = new Thread(ss); thread.start(); Thread.sleep(1000); thread.interrupt(); } } |
...
Code Block | ||
---|---|---|
| ||
class StopSocket implements Runnable { // ... public void run() { String string; try { synchronized (this.locklock) { while ((string = this.in.readLine()) != null) { // Blocks until end of stream (null) } } } catch (IOException ie) { // Forward to handler } finally { try { shutdown(); } catch (IOException e) { // Forward to handler } } } public void shutdown() throws IOException { this.socket.close(); } public static void main(String[] args) throws IOException, InterruptedException { StopSocket ss = new StopSocket(); Thread thread = new Thread(ss); thread.start(); Thread.sleep(1000); ss.shutdown(); } } |
...
Code Block | ||
---|---|---|
| ||
class StopSocket implements Runnable { private final SocketChannel sc; private final Object lock = new Object; public StopSocket() throws IOException { InetSocketAddressthis.sc addr = SocketChannel.open(new InetSocketAddress("somehost", 25); this.sc = SocketChannel.open(addr); } private final Object lock = new Object; public void run() { ByteBuffer buf = ByteBuffer.allocate(1024); try { synchronized (this.lock) { while (!Thread.interrupted()) { this.sc.read(buf); // ... } } } catch (IOException ie) { // Forward to handler } } public static void main(String[] args) throws IOException, InterruptedException { StopSocket ss = new StopSocket(); Thread thread = new Thread(ss); thread.start(); Thread.sleep(1000); thread.interrupt(); } } |
...