簡體   English   中英

從Java中的線程調用JMX連接?

[英]Calling JMX connection from thread in Java?

計划:創建一個管理線程,為用戶創建一個,每個線程都可以在main中調用。 如何從線程調用連接? 還是應該在其他地方進行此連接,以便我的線程可以看到它? 應該是這樣的: mbeanProxy.startBattle(500); 這就是我從主類中調用方法的方式,但是它在線程tho中不起作用。 服務器是使用MBean的JMX。

Client.java:

    public class Client {
public static final String HOST = "localhost";
public static final String PORT = "9119";
public static Scanner sc;

    public static void main(String[] args) throws IOException, MalformedObjectNameException {
        sc = new Scanner(System.in);
        Map<String, String[]> env = new HashMap<>();
        System.out.println("Login: ");
        String login = sc.nextLine();
        System.out.println("Password: ");
        String password = sc.nextLine();
        String[] credentials = {login, password};
        env.put(JMXConnector.CREDENTIALS, credentials);
        JMXServiceURL url =
            new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + HOST + ":" + PORT + "/jmxrmi");
        JMXConnector jmxConnector = JMXConnectorFactory.connect(url, env);
        MBeanServerConnection mbeanServerConnection = jmxConnector.getMBeanServerConnection();
        ObjectName mbeanName = new ObjectName("serveris:type=Serveris");
        ServerisMBean mbeanProxy =
            (ServerisMBean) MBeanServerInvocationHandler.newProxyInstance(
                mbeanServerConnection, mbeanName, ServerisMBean.class, true);

        System.out.print( mbeanProxy.toString());
        Object dummyObject = new Object();
        Runnable task = new PlayerThread("test", dummyObject);
        Thread worker = new Thread(task);
        worker.start();
        mbeanProxy.startBattle(500);
        jmxConnector.close();
    }

}

ServerisMBean.java

package client;
public interface ServerisMBean {
    public void startBattle(int token);
    public void stopBattle();
    public int getToken();
}

並且,如果有人發現我在編碼風格方面犯了任何錯誤,請告訴我,只是一個新手,並希望獲得有關如何使我在Java方面變得更好的信息。

我要做的就是通過這種方式獲取“ mbeanProxy”並將其發送到線程:

在主目錄中: Runnable task = new PlayerThread("test", dummyObject, mbeanProxy);

在線程中:您必須在代碼頂部( private final ServerisMBean mbeanProxy;

然后在同一線程的構造函數中: public PlayerThread(String vardas, Object dummyObject, ServerisMBean mbeanProxy1){ this.mbeanProxy = mbeanProxy1; } public PlayerThread(String vardas, Object dummyObject, ServerisMBean mbeanProxy1){ this.mbeanProxy = mbeanProxy1; }

我可以通過以下方式在線程內部調用它:

public void run() {
        System.out.println("test:"+mbeanProxy.getToken());}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM