public static void main(String[] args){ Runnable status_runnable=GenerateStatus();
Runnable session_runnable=MyThread(session);
Thread statusThread=Thread(status_runnable);//线程中放了任务
Thread session_thread=Thread(session_runnable);
statusThread.start();
session_thread.start();
}
两个类的实现如下,第一个是GenerateStatus
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
import
java.util.Random;
public
class
GenerateStatus
implements
Runnable{
private
String temperature;
private
String free_Space;
public
GenerateStatus(){
/*构造方法*/
}
/*线程中运行的程序*/
public
void
run() {
//这里因为实现接口这个必须实现
Random random=
new
Random();
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
(InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
第二个类MyThread
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
javax.websocket.Session;
java.io.IOException;
MyThread Runnable {
String ;
String ;
Session ;
MyThread(Session session) IOException {
.=session;
}
run() {
(){
{
Thread.();
} (InterruptedException e) {
e.printStackTrace();
}
System..println();
=StatusMap.();
=StatusMap.();
{
.getBasicRemote().sendText();
.getBasicRemote().sendText();
} (IOException e) {
e.printStackTrace();
}
}
}
}
|
PS:若只需一个线程,就可以直接建立个线程使其继承Thread,在主函数中直接调用。
statusThread.start();//这样就可以了。但是不能多个线程同时运行!
本文转自 神迹难觅 51CTO博客,原文链接:http://blog.51cto.com/ji123/2054650,如需转载请自行联系原作者