Biblioteca Java - Rev 8
Subversion Repositories:
package synchronousqueue;
import java.util.Random;
import java.util.concurrent.SynchronousQueue;
public class SynchronousTest {
public static void main(String[] args) {
SynchronousQueue<String> q = new SynchronousQueue<String>();
MessageGenerator mg = new MessageGenerator(q);
mg.start();
MessageReader mr1 = new MessageReader(q);
mr1.start();
}
}
class MessageGenerator extends Thread{
SynchronousQueue<String> q;
boolean active = true;
public MessageGenerator(SynchronousQueue<String> q) {
this.q = q;
}
public void run(){
Random r = new Random();
while(active){
int i = r.nextInt();
System.out.println("Add new object.");
try {
q.put(" Generated int="+i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Object added.");
}
}
}
class MessageReader extends Thread{
SynchronousQueue<String> q;
boolean active = true;
public MessageReader(SynchronousQueue<String> q) {
super();
this.q = q;
}
public void run(){
while(active){
try {
String s = q.take();
System.out.println("***Object received.Processing.");
int slp = (int)((Math.random()*10));
Thread.sleep(slp*1000);
System.out.println("***Object processed.");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
import java.util.Random;
import java.util.concurrent.SynchronousQueue;
public class SynchronousTest {
public static void main(String[] args) {
SynchronousQueue<String> q = new SynchronousQueue<String>();
MessageGenerator mg = new MessageGenerator(q);
mg.start();
MessageReader mr1 = new MessageReader(q);
mr1.start();
}
}
class MessageGenerator extends Thread{
SynchronousQueue<String> q;
boolean active = true;
public MessageGenerator(SynchronousQueue<String> q) {
this.q = q;
}
public void run(){
Random r = new Random();
while(active){
int i = r.nextInt();
System.out.println("Add new object.");
try {
q.put(" Generated int="+i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Object added.");
}
}
}
class MessageReader extends Thread{
SynchronousQueue<String> q;
boolean active = true;
public MessageReader(SynchronousQueue<String> q) {
super();
this.q = q;
}
public void run(){
while(active){
try {
String s = q.take();
System.out.println("***Object received.Processing.");
int slp = (int)((Math.random()*10));
Thread.sleep(slp*1000);
System.out.println("***Object processed.");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}