简体   繁体   English

在我的情况下使用线程池

[英]using thread pool in my case

I want to draw circles on the jpanel, where each circle should appear alternately on the random location with a different color and after for example 2000ms, it dies (disappears), and then appears a new one. 我想在jpanel上绘制圆圈,其中每个圆圈应该在随机位置上以不同的颜色交替出现,例如2000ms之后,它消失(消失),然后出现一个新的圆圈。

However, I want to use a thread pool with a 3 threads so that I can show 3 circles in the same time. 但是,我想使用一个具有3个线程的线程池,以便可以同时显示3个圆圈。

So now I'm not sure how should I execute CircleRunnable class and make this circles appear on the screen? 因此,现在我不确定如何执行CircleRunnable类并使该圆圈显示在屏幕上?

No, you shouldn't use multiple threads for this. 不,您不应为此使用多个线程。 Graphics isn't something that's generally multithreaded (as evidenced by Swing's Event/Paint thread). 图形通常不是多线程的(如Swing的事件/绘画线程所证明)。

Instead you should keep track of circles and their lifetimes in a suitable collection and handle that in a single thread. 相反,您应该在合适的集合中跟踪圆及其寿命,并在单个线程中进行处理。 For example creating a javax.swing.Timer and generating circles randomly each tick. 例如,创建一个javax.swing.Timer并在每个刻度上随机生成圆圈。

That way you can have hundreds of circles, and you won't shoot yourself in the foot with multithreading in a Swing program. 这样一来,您可以拥有数百个圆圈,而且您不会在Swing程序中使用多线程而步履蹒跚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM