使用管道,还是无法解决two producter , one consumer的问题
import java.util.*;
import java.io.*;//two producter , one consumerpublic class PipeTest { private static HashMap m = new HashMap();
private static PipedOutputStream pipeOut;
private static PipedInputStream pipeIn ;
public static void main(String[] args) {
try {
pipeOut = new PipedOutputStream();
pipeIn = new PipedInputStream(pipeOut);
System.out.println("Start sendThread . ");
//send Thread
new Thread() {
public void run() {
synchronized(this) {
try {
pipeOut.write(5);
} catch(Exception e) {}
}
}
}.start();
System.out.println("Start recvThread . ");
//recv Thread
new Thread() {
public void run() {
synchronized(this) {
try {
pipeOut.write(9);
} catch(Exception e) {}
}
}
}.start();
System.out.println("Start updateThread .");
//更新GUI线程
new Thread() {
public void run() {
try {
int result = pipeIn.read();
System.out.println("result : " + result);
m.put("..", result + "");
System.out.println("sizeOfHashMap : " + m.size() );
System.out.println(" m : " + m);
} catch(Exception e) {}
} }.start();
} catch(Exception e) {}
}
}运行结果:
sizeOfHashMap : 1
m : {..=5}
import java.util.*;
import java.io.*;//two producter , one consumerpublic class PipeTest { private static HashMap m = new HashMap();
private static PipedOutputStream pipeOut;
private static PipedInputStream pipeIn ;
public static void main(String[] args) {
try {
pipeOut = new PipedOutputStream();
pipeIn = new PipedInputStream(pipeOut);
System.out.println("Start sendThread . ");
//send Thread
new Thread() {
public void run() {
synchronized(this) {
try {
pipeOut.write(5);
} catch(Exception e) {}
}
}
}.start();
System.out.println("Start recvThread . ");
//recv Thread
new Thread() {
public void run() {
synchronized(this) {
try {
pipeOut.write(9);
} catch(Exception e) {}
}
}
}.start();
System.out.println("Start updateThread .");
//更新GUI线程
new Thread() {
public void run() {
try {
int result = pipeIn.read();
System.out.println("result : " + result);
m.put("..", result + "");
System.out.println("sizeOfHashMap : " + m.size() );
System.out.println(" m : " + m);
} catch(Exception e) {}
} }.start();
} catch(Exception e) {}
}
}运行结果:
sizeOfHashMap : 1
m : {..=5}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货