访问线程中的变量(Access variable in a thread)
我正在尝试使用任意数量的工作线程处理arraylist。 我想跟踪每个工作线程处理了多少项,并在一定数量后终止它们。 在工作线程类中为计数器声明一个变量并检查该计数器是一种有效的方法吗?
. . Thread t = new Thread(); t.start while(true){ if(t.counter >= 5){ return; } } . . class Thread{ int counter = 0; public void run { while(true){ do something.... counter++; } } }I'm trying process an arraylist using arbitrary number of worker threads. I would like to keep track of how many items each worker thread has processed and terminate them after a certain number. Would declaring a variable for counter inside the worker thread class and checking on that counter be a valid approach?
. . Thread t = new Thread(); t.start while(true){ if(t.counter >= 5){ return; } } . . class Thread{ int counter = 0; public void run { while(true){ do something.... counter++; } } }最满意答案
我就是这样做的:
int counter = 0; Thread t = new Thread(new Runnable(){ public void run { while(true){ doSomething... counter++ } } }); t.start(); while(true){ if(counter >= 5){ return; } }作为你的问题的答案...我不知道有什么方法可以访问另一个线程的runnable。 可能有,但上面的代码可以很好地工作。
This is how I would do it:
int counter = 0; Thread t = new Thread(new Runnable(){ public void run { while(true){ doSomething... counter++ } } }); t.start(); while(true){ if(counter >= 5){ return; } }As an answer to your question... i do not know of any way to access the runnable of another thread. There might be, but the above code will work just fine hopefully.
更多推荐
发布评论