如何访问正在运行的线程的属性值 [英] How can I access the property value of a running Thread
本文介绍了如何访问正在运行的线程的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个线程运行了很长时间(5-6 分钟).
I have a Thread that run for a long time (5-6 min).
public class ExportThread implements Runnable {
private Integer totalExport = 0;
@Override
public void run() {
try {
exportCorner();
} catch (Exception e) {
e.printStackTrace();
}
}
private void exportCorner() {
List<MyObject> list = ......
for(MyObject o : list){
.......
totalExport++;
}
}
}
这个线程从另一个类运行.如何在很小的间隔后一次又一次地获得 totalExport ?
This Thread runs from another class. How can I get the totalExport again and again after a small interval ?
推荐答案
只需向线程类添加一些 getter 即可获得它,正如@RomanKonoval 所说,它需要同步
Simply you get it by adding some getters to your thread class, as @RomanKonoval said it need to be synchronized
public class ExportThread implements Runnable {
private Integer totalExport = 0;
@Override
public void run() {
try {
exportCorner();
} catch (Exception e) {
e.printStackTrace();
}
}
private void exportCorner() {
List<Integer> list = ......
for(Integer i : list){
totalExport += i;
}
}
public synchronized Integer getTotalExport(){
return this.totalExport;
}
}
从你的其他班级你可以使用类似的东西
From your other class you can use something like that
import java.util.*;
public class MainClass {
public static void main(String[] args) {
ExportThread exportThread = new ExportThread();
Thread t = new Thread(exportThread);
t.start();
TimerTask timerTask= new MyTimerTask(exportThread);
Timer timer = new Timer();
timer.scheduleAtFixedRate(tasknew,new Date(),1000);
}
}
那么你可能需要实现你的定时器任务
Then you may need to implement your timer task
public class MyTimerTask extends TimerTask {
private ExportThread exportThread;
public MyTimerTask(ExportThread exportThread){
this.exportThread = exportThread;
}
@Override
public void run() {
System.out.println(exportThread.getTotalExports());
}
}
这篇关于如何访问正在运行的线程的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文