Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Java thread lock example

View ThreadLock.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package threadlock;
 
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
 
/**
*
* @author vcamaral
*/
public class ThreadLock extends Thread {
private int currentThread;
public ThreadLock(int i) {
this.currentThread = i;
}
@Override
public void run() {
for(int i = this.currentThread; i < this.currentThread + 3; i++) {
try {
Socket s = new Socket("127.0.0.1", 9876);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
DataInputStream dis = new DataInputStream(s.getInputStream());
dos.writeUTF("Hello! I'm a client " + i + "!\n");
System.out.println(dis.readUTF());
} catch (UnknownHostException ex) {
Logger.getLogger(ThreadLock.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ThreadLock.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
for(int i = 0; i < 12; i += 3) {
ThreadLock tl = new ThreadLock(i);
tl.start();
}
}
}
View ThreadLock.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
var net = require("net")
, fs = require("fs")
, filename = "messages.txt";
 
var server = net.createServer(function(socket) {
console.log("== Client connected");
 
socket.on("data", function(data) {
var message = data.toString();
 
console.log("== Client sent:", message);
 
fs.createWriteStream(filename, { flags: "a" }).write(message);
fs.readFile(filename, function(err, data) {
socket.write(message);
socket.end();
});
});
 
socket.on("end", function() {
console.log("== Client disconnected");
});
}).listen(9876);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.