publicstaticvoidmain(String[]args){Runnablestatus_runnable=GenerateStatus();Runnablesession_runnable=MyThread(session);ThreadstatusThread=Thread(status_runnable);//线程中放了任务Threadsession_thread=Thread(session_runnable);statusThread.start();session_thread.start();

}

两个类的实现如下,第一个是GenerateStatus

importjava.util.Random;publicclassGenerateStatusimplementsRunnable{privateStringtemperature;privateStringfree_Space;publicGenerateStatus(){/*构造方法*/}/*线程中运行的程序*/publicvoidrun(){//这里因为实现接口这个必须实现Randomrandom=newRandom();while(true){temperature=((Integer)(random.nextInt(70)+20)).toString();free_Space=((Integer)(random.nextInt(100)+1)).toString()+"G";StatusMap.put("temperature",temperature);StatusMap.put("free_Space",free_Space);System.out.println("test");try{Thread.sleep(1000);}catch(InterruptedExceptione){e.printStackTrace();}}}}



第二个类MyThread


javax.websocket.Session;java.io.IOException;MyThreadRunnable{String;String;Session;MyThread(Sessionsession)IOException{.=session;}run(){(){{Thread.();}(InterruptedExceptione){e.printStackTrace();}System..println();=StatusMap.();=StatusMap.();{.getBasicRemote().sendText();.getBasicRemote().sendText();}(IOExceptione){e.printStackTrace();}}}}




PS:若只需一个线程,就可以直接建立个线程使其继承Thread,在主函数中直接调用。

ThreadstatusThread=newMyThread(session);statusThread.start();//这样就可以了。但是不能多个线程同时运行!