我只是试图向另一个对象发送消息,但除非我错过了一个重要因素,否则它并没有完全改变。我有一个类来设置数字和另一个类来获取,获取的类取决于设置的正确数字,但是尽管 set 方法在命令行中返回 0,但另一个对象在使用 get 方法时返回 1。这是保存两个方法的关闭类,每个方法都从类 A 和类 B 调用
public class Close {
static int close =1;
public synchronized void setClose(int x, Client)
{
/*
while(turn !=0){
try{
wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}*/
close = x;
System.out.println("set "+close);
}
public synchronized int getClose(ClientHandeler)
{
int x;
/*
while(turn==0){
try{
wait();
}catch(Exception e)
}
}*/
System.out.println("get "+close);
x = close;
return x;
}
}
这是我希望从中获取接近整数的处理程序类
import java.io.*;
import java.net.*;
import java.util.*;
public class ClientHandler implements Runnable {
private BufferedReader reader;
private Socket sock;//refering to socket class
//listens for the socket
private Server server; // call-back reference to transmit message to all clients
Client c = new Client();
public ClientHandler(Socket clientSocket, Server serv) {
try {
sock = clientSocket;
server = serv;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void run() {
String message;
try {
int x = c.c.getClose(this);
while(x!=0){
x = c.c.getClose(this);//calls client and within client there is the close
System.out.println(x);
Thread ct= Thread.currentThread();
ct.sleep(3000);
while ((message = reader.readLine()) != null) {
System.out.println("read " + message);
server.tellEveryone(message);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
可能它们都不使用相同的 Close 对象。
Close close = new Close();
然后确保两者都使用相同的关闭对象!
如果无法做到这一点,则可以将字段关闭设置为静态:
public class Close {
static int close;
你可以只使用AtomicInteger。
public class Close {
AtomicInteger close = new AtomicInteger(1);
public void setClose(int x)
{
/*
while(turn !=0){
try{
wait();
}
catch(Exception e)
{
e.printStackTrace();
}*/
close.set(x);
System.out.println("set "+close.get());
}
public int getClose()
{
int x;
/*
while(turn==0){
try{
wait();
}catch(Exception e)
}*/
System.out.println("get "+close.get());
x = close.get();
return x;
}
试试...
static int close = 1;
这样,对于 Close 类的所有实例,将只有一个 int close 副本。 添加使用此类的代码会有所帮助,我猜您正在为每个操作实例化新副本,这导致了您的问题。
我真的不明白你的问题。 你能给出一些关于你如何使用这个类的片段吗?
但是,看起来您很可能没有从所谓的 A 类和 B 类访问相同的实例。
这就像A在一张纸上写东西,而B在阅读另一张纸。 当然,A写的东西是B无法读的。