将变量从Java中的级联类写回调用方法

将变量从Java中的级联类写回调用方法,java,multithreading,variables,scope,Java,Multithreading,Variables,Scope,我在Java中遇到以下问题: 一个类的main方法调用另一个类的main方法。现在,第二个类创建了一个新的线程类。在这个线程类中,我应该能够改变一个布尔值,这个布尔值在主类中也是已知的。当该布尔值发生更改时,必须调用某些方法。我用静电笔试过了,但似乎不起作用 下面的代码给出了三个类,希望能澄清我的情况: Client.java package be.sylvainvansteelandt.mp.roleassigner; import java.util.ArrayList; import

我在Java中遇到以下问题:

一个类的main方法调用另一个类的main方法。现在,第二个类创建了一个新的线程类。在这个线程类中,我应该能够改变一个布尔值,这个布尔值在主类中也是已知的。当该布尔值发生更改时,必须调用某些方法。我用静电笔试过了,但似乎不起作用

下面的代码给出了三个类,希望能澄清我的情况:

Client.java

package be.sylvainvansteelandt.mp.roleassigner;

import java.util.ArrayList;

import be.sylvainvansteelandt.mp.configuration.*;
import be.sylvainvansteelandt.mp.hardware.*;
import be.sylvainvansteelandt.mp.networking.*;

public class Client {


// fields
// 55678 = local client/server port for this project
static final int LOCAL_CLIENTSERVER_PORT = 55678;

// Router internal interface port
static final int ROUTER_INT_PORT = 55679;

//this is static boolean i tried to use
static boolean flag = false;

public static void main(String[] args) {

    ClientConfigListener.main(null);

    while (true) {
        if(flag == true){
            //set signal back to false
            flag = false;
            Configuration config = IP.getGlobalConfiguration("192.168.0.191", ROUTER_INT_PORT, 100);
            doClient(config.getMaster_count());
        }           
    }
}

// Search all hosts on the subnet with a live Server and get from each the
// HardwareInfo, and rank them based on the score derivated from the HardwareInfo, as to get
// the role of each host, being master or slave
private static void doClient(int mastercount) {
    try {
        String localIP = HardwareInfo.getNetworkInterface("192.168.0.0", 24);
        String[] allIps = IP.getHosts(localIP, 24);
        ArrayList<String> reachableIPs = IP.reachableHosts(allIps, LOCAL_CLIENTSERVER_PORT);
        System.out.println("List of reachable IP's:" + System.lineSeparator());
        for (String ip : reachableIPs) {
            System.out.println("Host: " + ip);
        }
        System.out.println(System.lineSeparator());
        ArrayList<HardwareInfo> hostSpecs = IP.getSpecsFromReachableHosts(reachableIPs, LOCAL_CLIENTSERVER_PORT,
                10);
        hostSpecs = HardwareInfo.calculateResourceScore(hostSpecs, 0.4, 0.4, mastercount);
        System.out.println("Overview of specs for each host:" + System.lineSeparator());
        for (HardwareInfo h : hostSpecs) {
            System.out.println(h.toString());
        }
    } catch (IllegalArgumentException e) {
        System.out.println("not a valid ip address!");
    }
}
}
package be.sylvainvansteelandt.mp.roleassigner;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ClientConfigListener {

// 55677 = client config listener port for this project
static final int CLIENT_CONFIG_LISTENER_PORT = 55677;

@SuppressWarnings("resource")
public static void main(String[] args) {

    // Open socket

    ServerSocket serverSocket = null;
    Socket socket = null;

    try {
        serverSocket = new ServerSocket(CLIENT_CONFIG_LISTENER_PORT);
        System.out.println("Listener started and is ready to accept connections ...");
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Accept connections
    while (true) {
        try {
            socket = serverSocket.accept();
            System.out.println("Listener accepted a connection.");
        } catch (IOException e) {
            System.out.println("An I/O error occured: " + e);
        }
        // new thread for a client
        new ClientConfigListenerThread(socket).start();
    }

}

}
package be.sylvainvansteelandt.mp.roleassigner;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class ClientConfigListenerThread extends Thread {

// fields
protected Socket socket;
protected String line = null;
protected ObjectOutputStream oos = null;
protected ObjectInputStream ois = null;

// constructor
public ClientConfigListenerThread(Socket clientSocket) {

    this.socket = clientSocket;

}

public void run() {
    try {
        oos = new ObjectOutputStream(socket.getOutputStream());
        ois = new ObjectInputStream(socket.getInputStream());

    } catch (IOException e) {
        System.out.println("There was a problem creating the input- and outputstreams from the socket.");
        return;
    }

    try {
        String s = (String) ois.readObject();
        System.out.println("INCOMMING MESSAGE: " + s);

        if (s.equalsIgnoreCase("CONFIGISSET")) {
            // write here to Client class (a signal, like a boolean or
            // something)
            Client.flag = true;
        }
    } catch (IOException e) {
        System.out.println("IO Error/ Client " + this.getName() + " terminated abruptly");
    } catch (NullPointerException e) {
        System.out.println("Client " + this.getName() + " Closed");
    } catch (ClassNotFoundException e) {
        System.out.println("ClassNotFoundException");
    } finally {
        try {
            System.out.println("Connection Closing..");
            if (ois != null) {
                ois.close();
                System.out.println("Socket Input Stream Closed");
            }
            if (oos != null) {
                oos.close();
                System.out.println("Socket Output Stream Closed");
            }
            if (socket != null) {
                socket.close();
                System.out.println("Socket Closed");
            }

        } catch (IOException ie) {
            System.out.println("Socket Close Error");
        }
    }
}
}
ClientConfigListenerThread.java

package be.sylvainvansteelandt.mp.roleassigner;

import java.util.ArrayList;

import be.sylvainvansteelandt.mp.configuration.*;
import be.sylvainvansteelandt.mp.hardware.*;
import be.sylvainvansteelandt.mp.networking.*;

public class Client {


// fields
// 55678 = local client/server port for this project
static final int LOCAL_CLIENTSERVER_PORT = 55678;

// Router internal interface port
static final int ROUTER_INT_PORT = 55679;

//this is static boolean i tried to use
static boolean flag = false;

public static void main(String[] args) {

    ClientConfigListener.main(null);

    while (true) {
        if(flag == true){
            //set signal back to false
            flag = false;
            Configuration config = IP.getGlobalConfiguration("192.168.0.191", ROUTER_INT_PORT, 100);
            doClient(config.getMaster_count());
        }           
    }
}

// Search all hosts on the subnet with a live Server and get from each the
// HardwareInfo, and rank them based on the score derivated from the HardwareInfo, as to get
// the role of each host, being master or slave
private static void doClient(int mastercount) {
    try {
        String localIP = HardwareInfo.getNetworkInterface("192.168.0.0", 24);
        String[] allIps = IP.getHosts(localIP, 24);
        ArrayList<String> reachableIPs = IP.reachableHosts(allIps, LOCAL_CLIENTSERVER_PORT);
        System.out.println("List of reachable IP's:" + System.lineSeparator());
        for (String ip : reachableIPs) {
            System.out.println("Host: " + ip);
        }
        System.out.println(System.lineSeparator());
        ArrayList<HardwareInfo> hostSpecs = IP.getSpecsFromReachableHosts(reachableIPs, LOCAL_CLIENTSERVER_PORT,
                10);
        hostSpecs = HardwareInfo.calculateResourceScore(hostSpecs, 0.4, 0.4, mastercount);
        System.out.println("Overview of specs for each host:" + System.lineSeparator());
        for (HardwareInfo h : hostSpecs) {
            System.out.println(h.toString());
        }
    } catch (IllegalArgumentException e) {
        System.out.println("not a valid ip address!");
    }
}
}
package be.sylvainvansteelandt.mp.roleassigner;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ClientConfigListener {

// 55677 = client config listener port for this project
static final int CLIENT_CONFIG_LISTENER_PORT = 55677;

@SuppressWarnings("resource")
public static void main(String[] args) {

    // Open socket

    ServerSocket serverSocket = null;
    Socket socket = null;

    try {
        serverSocket = new ServerSocket(CLIENT_CONFIG_LISTENER_PORT);
        System.out.println("Listener started and is ready to accept connections ...");
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Accept connections
    while (true) {
        try {
            socket = serverSocket.accept();
            System.out.println("Listener accepted a connection.");
        } catch (IOException e) {
            System.out.println("An I/O error occured: " + e);
        }
        // new thread for a client
        new ClientConfigListenerThread(socket).start();
    }

}

}
package be.sylvainvansteelandt.mp.roleassigner;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class ClientConfigListenerThread extends Thread {

// fields
protected Socket socket;
protected String line = null;
protected ObjectOutputStream oos = null;
protected ObjectInputStream ois = null;

// constructor
public ClientConfigListenerThread(Socket clientSocket) {

    this.socket = clientSocket;

}

public void run() {
    try {
        oos = new ObjectOutputStream(socket.getOutputStream());
        ois = new ObjectInputStream(socket.getInputStream());

    } catch (IOException e) {
        System.out.println("There was a problem creating the input- and outputstreams from the socket.");
        return;
    }

    try {
        String s = (String) ois.readObject();
        System.out.println("INCOMMING MESSAGE: " + s);

        if (s.equalsIgnoreCase("CONFIGISSET")) {
            // write here to Client class (a signal, like a boolean or
            // something)
            Client.flag = true;
        }
    } catch (IOException e) {
        System.out.println("IO Error/ Client " + this.getName() + " terminated abruptly");
    } catch (NullPointerException e) {
        System.out.println("Client " + this.getName() + " Closed");
    } catch (ClassNotFoundException e) {
        System.out.println("ClassNotFoundException");
    } finally {
        try {
            System.out.println("Connection Closing..");
            if (ois != null) {
                ois.close();
                System.out.println("Socket Input Stream Closed");
            }
            if (oos != null) {
                oos.close();
                System.out.println("Socket Output Stream Closed");
            }
            if (socket != null) {
                socket.close();
                System.out.println("Socket Closed");
            }

        } catch (IOException ie) {
            System.out.println("Socket Close Error");
        }
    }
}
}

我将发布一些更抽象和简短的示例,希望这些示例有意义,而不是完全复制您的代码

我喜欢使用的类似于此的技术只是在过程中传递对类的引用:

ClassA-做某事,然后将标志设置为true

public class ClassA {

    // Thread-Safe boolean
    private AtomicBoolean flag = new AtomicBoolean(false);

    public ClassA() {

    }

    public void doSomeOperation() {
        System.out.println("Starting thread.");

        // Operation Thread
        Thread op = new Thread( () -> {
            // Do something
            for(int i = 0; i < 10000; i++)
                System.out.println("Thread is still running...");

            // Set the flag
            flag.set(true);
        });

        // Start Thread
        op.start();
    }

    public boolean isFlagTrue() {
        flag.get();
    }

}
Main类-创建ClassA和ClassB,然后开始ClassA的操作

public class Main {

    public static void main (String ... args) {
        ClassA a = new ClassA();
        ClassB b = new ClassB(a);

        a.doSomeOperation();
    }
}

原子布尔-

您的
客户端
while循环非常紧密,将消耗100%的CPU您能解释一下我如何用您的技术解决这个问题吗?我试着用AtomicBoolean将代码中的标志以及代码中的get和引用更改为标志,但这似乎不起作用。