解决方案 »
- java程序中 已知txt文件名 如何获取文件的路径
- 能推荐个java(SSH2协议)访问Linux的客户端开源控件吗?类似FTPClient
- substance.jar怎么用
- JAVA要下载一个什么才能和SQL2000连接?
- tomcat在外网发布工程出问题
- 挽救青春生命奉献社会爱心!!!!!!!!!!!!!!!
- Java串口通讯,为什么列不出串口和并口?
- 做运算时,10的2次方,表达式怎么写?
- 提问:有没有方法将String中的所有空格一次性去掉?
- int code = conn.getResponseCode(); 程序貌似卡这里了,怎么解决??谢谢
- Java读取控制 error code=109 message=管道已结束
- 进程 同步问题
得根据不同的粒度来加锁public boolean operate1()和public boolean operate2()是否互斥?还是说:只要一个线程处于connect状态,别的线程都不能做任何操作?只有等disconnect以后,别的线程才可以操作?
也就是说只要有线程在使用operate1(),别的任何线程使用connect都会导致异常。
private String ip;
private int port;
private static Demo instance = new Demo();
private Demo(){
}
public Demo getInstance(){
return this.instance;
} // 连接设备
public boolean connect(String ip, int port) {
synchronized (this) {
this.ip = ip;
this.port = port;
// 这里是连接设备的代码,根据返回值判定连接状态
return true;
}
} // 操作设备
public boolean operate1() {
synchronized (this) {
// 根据IP地址操作设备,返回操作结果
return false;
}
} // 操作设备
public boolean operate2() {
synchronized (this) {
// 根据IP地址操作设备,返回操作结果
return false;
}
} // 断开设备
public boolean disconnect() {
synchronized (this) {
// 断开设备连接
return true;
}
}
}
private String ip;
private int port;
private static Demo instance = new Demo();
private Demo(){
}
public Demo getInstance(){
return this.instance;
} // 连接设备
public boolean connect(String ip, int port) {
synchronized (this) {
this.ip = ip;
this.port = port;
// 这里是连接设备的代码,根据返回值判定连接状态
return true;
}
} // 操作设备
public boolean operate1() {
synchronized (this) {
// 根据IP地址操作设备,返回操作结果
return false;
}
} // 操作设备
public boolean operate2() {
synchronized (this) {
// 根据IP地址操作设备,返回操作结果
return false;
}
} // 断开设备
public boolean disconnect() {
synchronized (this) {
// 断开设备连接
return true;
}
}
}
你这种做法虽然是单例,而且每个方法都加了锁。
但是你却没有办法杜绝这种访问。
比如访问顺序是
connect
connect
operate1
operate2
disconnect
operate1
operate2
disconnect因为你是每个方法单独加锁的,你是没有办法保证方法的调用顺序的。
试试这样行不行,利用静态类特性加互斥锁。
在 Demo 类中写一个静态内部类,这个内部类才是真正实现连接设备,Demo 只是调用该内部类的方法。public class Demo{
private String ip;
private int port; private Demo(){}
private static class DemoHolder{
private static Demo instance = new OnlyModel();
} public static Demo getInstance(){
return OnlyModelHolder.instance;
} pirvate static class Connect{
// Connect的连接设备
public static boolean connect(String ip, int port) {
...
} // Connect的操作设备
public static boolean operate1() {
...
}
} public static boolean connect(String ip, int port) {
synchronized(Connect.class){
Connect.connect();
}
} public static boolean operate1() {
synchronized(Connect.class){
Connect.operate1();
}
}
}
应该是你说的第一种情况,一个线程用connect方法连接设备,然后做一些操作采集数据,最后用disconnect断开设备连接,在这过程中,不允许其它线程使用这个类里面的任意方法。
//如果这些方法让其他类用,那就将其私有化
private boolean connect(String ip, int port) {
...
}
private boolean operate1() {
...
} public synchronized boolean operate(String ip, int port){
if(!connect(String ip, int port))
retuen false; if(!operate1()){
retuen false;
}
//...
return true;
}