访问线程中的变量(Access variable in a thread)

编程入门 行业动态 更新时间:2024-10-21 05:43:41
访问线程中的变量(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.

更多推荐

本文发布于:2023-07-20 02:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1192124.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   变量   Access   variable   thread

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!