62,621
社区成员
发帖
与我相关
我的任务
分享class HL7ServerAdvanced{
public String receivemsgstring;
//获取内部类,SafeStorage是一个接口
public SafeStorage getSafeStorage() {
return new MySafeStorge();
}
class MySafeStorge implements SafeStorage{
//内部类中想要同步的函数
public void store(Transportable theMessage) throws FileNotFoundException,IOException{
receivemsgstring = "abc";
FileOutputStream fos = new FileOutputStream("recv.txt", true);
fos.write(receivemsgstring.getBytes());
fos.flush();
if (fos != null) {
fos.close();
fos = null;
}
}
public static void main(String[] args) {
final HL7ServerAdvanced hsd = new HL7ServerAdvanced();
class PrintSubThread extends Thread {
public void run() {
try {
while (true) {
sleep(500); //想让StoreSubThread线程先执行,目的是对receivemsgstring赋值
if (hsd.receivemsgstring != null ) {
System.out.println(hsd.receivemsgstring);
hsd.receivemsgstring = null;
}
}
}
catch (InterruptedException iex) {
iex.printStackTrace();
}
}
}
class StoreSubThread extends Thread{
public void run(){
//调用内部类中的方法
hsd.getSafeStorage().store();
}
}
PrintSubThread pst = new PrintSubThread();
StoreSubThread sst = new StoreSubThread();
pst.start();
sst.start();
}
}
//在类中的函数
public void store(Transportable theMessage){
synchronized(lock){
...
}
}
//在要访问receivemsgstring的函数在类外
class HL7Application{
class HL7ServerAdvanced hsd = new HL7ServerAdvanced();
class PrintSubThread extends Thread {
public void run() {
while (true) {
sleep(500); //想让StoreSubThread线程先执行,目的是对receivemsgstring赋值
synchronized(hsd.lock){
if (hsd.receivemsgstring != null ) {
System.out.println(hsd.receivemsgstring);
hsd.receivemsgstring = null;
}
}
}
}
}
}class PrintSubThread extends Thread {
public void run() {
while (true) {
//sleep(500); //想让StoreSubThread线程先执行,目的是对receivemsgstring赋值
synchronized(hsd.lock){
hsd.lock.wait();
if (hsd.receivemsgstring != null ) {
System.out.println(hsd.receivemsgstring);
hsd.receivemsgstring = null;
}
}
}
}
}public void store(Transportable theMessage) {
synchronized(lock){
//函数中的其他内容.........
lock.notifyAll();
}
}public String receivemsgstring;
public Object lock = new Object(); // 这个就是锁。synchronized(lock){
...
}