Monday, 9 February 2009

Advanced Thread Programming: Synchronization

import java.util.*;

public class Que {

/**
* @param args
*/
public static void main(String[] args) {

mapQ q = new mapQ();

new genQ(q);
new conQ(q);
}
}

////////////////// the commodity Queue /////////////////
class mapQ {

String s;
LinkedList que = new LinkedList();

synchronized void put(String s) {

if (que.size()>10)
try {
wait();
}
catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
que.addLast(s);
System.out.println("Put: " + s);
notify();
}

synchronized String get() {

if (que.isEmpty())
try {
wait();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
String temps = (String) que.removeFirst();
//System.out.println(que);
System.out.println("Got: " + temps);
notify();

return temps;
}
}

//////////////// producer /////////////////////
class genQ implements Runnable {
mapQ q;

genQ(mapQ q) {
this.q=q;
new Thread(this, "Producer").start();
}
public void run() {
int i=0;

while(true) {
int tempi = i++;
q.put(Integer.toString(tempi));
}
}
}

/////////////// consumer ///////////////////////
class conQ implements Runnable {
mapQ q;

conQ(mapQ q) {
this.q=q;
new Thread(this, "Consumer").start();
}

public void run() {
while(true) {
q.get();
}
}
}

Sunday, 1 February 2009

Echo Server/Client example

Client side
Server side
Server txt (as database)

Thread: hellothreads

HelloThread1
HelloThread2