简体   繁体   English

Java中每个类的线程(多线程?)

[英]A thread per class in Java(multithreading?)

I have a question. 我有个问题。 I am planning on creating a program which would have multiple classes(for each object like cars/player/enemies etc), and I wanted to ask, is it a good idea to create a thread in each of those classes? 我打算创建一个具有多个类的程序(对于每个对象,例如汽车/玩家/敌人等),我想问一下,在每个类中创建一个线程是一个好主意吗? I read that some Java VM support around 6500 threads, but would a mediocore laptop be able to support about 10-20 of them? 我读到一些Java VM支持大约6500个线程,但是mediocore笔记本电脑能够支持大约10-20个线程吗?

I think you should step back and do some more thinking/learning here. 我认为您应该退后一步,在这里做更多的思考/学习。

You see, threads are a programming mean used to enable "parallel" processing on some level. 您会看到,线程是一种用于在某种程度上启用“并行”处理的编程方式 They are not inherently "good" or "bad". 它们并不是天生的“好”或“坏”。

In other words: you don't just "use one thread per class/object" because you could do so. 换句话说:您不只是“每个类/对象使用一个线程”,因为您可以这样做。

You would only do that because you have a problem to solve where doing so would make sense . 你只做到这一点,因为你必须解决一个问题,这样才有意义

And generally spoken: such an idea doesn't make much sense in the first place. 通常来说:这样的想法一开始并没有多大意义。

You see, the idea of "each object/class" having its "own activity" that "drives" them is addressed by frameworks such as akka . 您会发现,“每个对象/类”具有“驱动”它们的“自身活动”的想法已通过akka之类的框架解决 And be assured: whatever you could come up with - such products such as akka would be more robust, more performant, more everything ... 放心:无论您能想到什么-akka之类的产品都将更加强大,性能更高,更多……

The real answer here; 真正的答案在这里; as said: you should step back and first understand your actual requirements. 如前所述:您应该退后一步,首先了解您的实际需求。 And then you carefully look into existing technologies in order to design a reliable, robust solution. 然后,您仔细研究现有技术,以设计可靠,强大的解决方案。

As for example, there are such things as Threadpools or the whole ExecutorService infrastructure that allow you to do things in parallel without the effort of managing Thread objects yourself. 例如,诸如Threadpools或整个ExecutorService基础结构之类的东西使您可以并行执行操作,而无需自己管理Thread对象。 You should very much prefer to build on something like that, instead of just pushing "bare metal" threads into your classes. 您应该非常喜欢建立类似的东西,而不仅仅是将“裸机”线程推入类中。

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

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