Java中的线程(Threads in Java)

我今天在一次采访中被问到Java中的Thread概念? 问题是......

  1. 什么是线程?
  2. 我们为什么要穿线?
  3. 线程上的实时示例。
  4. 我们可以在Spring框架服务类中创建线程吗?
  5. 可以弹性调用线程?

除了Thread的定义之外,我没有回答任何问题,我也是从互联网上学到的。

任何人都可以解释清楚这一点。

更新

线程和普通Java类有什么区别? 为什么我们需要线程...我可以在线程中执行业务逻辑吗? 我可以在线程中调用不同的类方法吗?


I was today asked in an interview over the Thread concepts in Java? The Questions were...

  1. What is a thread?
  2. Why do we go for threading?
  3. A real time example over the threads.
  4. Can we create threads in Spring framework service class.
  5. Can flex call a thread?

I did not answer any questions apart from definition of Thread, that too I just learnt from internet.

Can anyone explain me clearly over this.

Update:

What is a difference between a thread and a normal java class. why do we need threading... can i execute business logic in threads. Can i call a different class methods in Threads.


原文:https://stackoverflow.com/questions/2865315
2023-05-15 06:05

满意答案

它不是#1或#2。 我打赌它是#4,最有意义的是监视主循环外部的CPU使用情况,并在达到限制时将其杀死。 #3需要在screeps服务器上执行“语句级”事务的复杂代码。 正如你发现的那样,模拟器没有CPU限制。

大多数玩家通过简单地在主循环中尽早放置关键代码来解决这个问题,例如塔码先出现,然后产生代码,然后蠕动移动/工作。 这也可以防止代码中的未捕获异常,因为最重要的功能将(希望)已经执行。 尽管这对于CPU限制来说是一个糟糕的解决方案,但在我看来,一旦使用了存储桶中的所有CPU并且不断达到常规限制,您的代码就会像跳过每第二个tick一样。

我现在没有CPU问题(我有一个订阅),但是我可以通过将CPU密集型代码放到最后来解决这个问题,并且如果可能的话,只有在您的存储桶中有足够的CPU时才执行它,距离你的500个CPU每刻度限制不远。 它也有助于产生更大的毛刺,对于寻找或者甚至正好运动(每次移动0.2次)占用相当一部分CPU以及更大的毛刺意味着更少的毛刺是很常见的。


Case 4 by default, but modifiable to case 2.5

As nehegeb and dwurf suspected, and experiments with a private server have confirmed, the default behaviour is case 4. Changes to both game state and Memory that occurred before the interruption are committed.

However, the running of the default JSON serialize by the server main loop is controlled by the existence of an undocumented key '_parsed' in RawMemory; the key's value is a reference to Memory. Deleting the key at the start of the script's main loop and restoring it at the end has the effect of making the whole set of Memory changes made by the script's main loop atomic i.e. case 2.5:

module.exports.loop = function()
{
  // Run the default JSON deserialize. This also creates a key '_parsed' in
  // RawMemory - that '_parsed' key and Memory refer to the same object, and the
  // existence of the '_parsed' key tells the server main loop to run the
  // default JSON serialize.
  Memory;

  // Disable the default JSON serialize by deleting the key that tells the
  // server main loop to run it.
  delete RawMemory._parsed;

  ...

  // An example of code that would be wrong without a way to make it CPU limit
  // robust:

  mySpawn.memory.queue.push('harvester');
  // If the script is interrupted here, myRoom.memory.harvesterCreepsQueued is
  // no longer an accurate count of the number of 'harvester's in
  // mySpawn.memory.queue.
  myRoom.memory.harvesterCreepsQueued++;

  ...

  // Re-enable the default JSON serialize by restoring the key that tells the
  // server main loop to run it.
  RawMemory._parsed = Memory;
};

相关问答

更多

在Screeps中,是否强制执行CPU限制以允许写入CPU限制健壮代码?(In Screeps, is CPU limit enforced in a way that allows CPU limit robust code to be written?)

它不是#1或#2。 我打赌它是#4,最有意义的是监视主循环外部的CPU使用情况,并在达到限制时将其杀死。 #3需要在screeps服务器上执行“语句级”事务的复杂代码。 正如你发现的那样,模拟器没有CPU限制。 大多数玩家通过简单地在主循环中尽早放置关键代码来解决这个问题,例如塔码先出现,然后产生代码,然后蠕动移动/工作。 这也可以防止代码中的未捕获异常,因为最重要的功能将(希望)已经执行。 尽管这对于CPU限制来说是一个糟糕的解决方案,但在我看来,一旦使用了存储桶中的所有CPU并且不断达到常规限...

如何限制进程在Windows上的CPU使用率?(How do you limit a process' CPU usage on Windows? (need code, not an app))

非常简单,它可以像这样工作: 用一些合理的小等待时间(可能是100ms)创建一个定期等待定时器。 通过调用一次GetProcessTimes为每个相关进程获取“最后”值。 永远循环,阻止定时器。 每次你醒来: 如果 GetProcessAffinityMask返回0,则调用SetProcessAffinityMask(old_value) 。 这意味着我们在上一次迭代中暂停了这一过程,现在我们给它一次再次运行的机会。 否则调用GetProcessTimes来获取“当前”值 调用GetSystemT...

Python - 限制脚本的CPU使用率(Python - Limit cpu usage for a script)

也许尝试Python的“ 资源 ”包? 资源包基本上是UNIX中“setrlimit”的概括。 所以你可以设置CPU /内存使用限制等。 有关UNIX中的“setrlimit”的更多信息 谢谢@Stephane指出,这实际上是我的第一个答案。 Maybe try Python's "resource" package ? The resource package is basically a wraparound of "setrlimit" in UNIX. So you can set con...

限制python多处理中的总CPU使用率(Limit total CPU usage in python multiprocessing)

解决方案取决于你想要做什么。 这里有几个选项: 过程的优先级较低 你可以nice的子过程。 这样,尽管他们仍然会吃掉100%的CPU,但当您启动其他应用程序时,操作系统会优先考虑其他应用程序。 如果您想在笔记本电脑的背景上运行大量计算工作,并且不关心CPU风扇一直在运行,那么使用psutils设置nice值是您的解决方案。 这个脚本是一个测试脚本,它可以在所有内核上运行足够的时间,这样你就可以看到它的行为。 from multiprocessing import Pool, cpu_count i...

多处理 - 限制CPU使用率(Multiprocessing - limit CPU usage)

考虑使用multiprocessing.pool.ThreadPool 。 它提供与multiprocessing.Pool相同的API,但将工作负载抽象为线程集合。 请注意,如果您的CPU支持超线程,那么它很可能会通过物理内核分配工作负载。 Consider using multiprocessing.pool.ThreadPool. It provides the same API as multiprocessing.Pool but abstracts the workload to a ...

限制CPU使用率的线程数(Number of threads to limit CPU usage)

CPU使用率为50%并不一定意味着线程数需要为N_Cores / 2.在处理I / O时,CPU在等待数据从设备到达时会浪费很多周期。 因此,您需要一个工具来测量实际CPU使用率,并且通过实验,您可以增加线程数,直到实际CPU使用率达到50%。 针对Linux的perf就是这样一个工具。 这个问题解决了这个问题。 另外一定要收集统计系统: perf记录-a 。 您感兴趣的是CPU发出并执行尽可能多的指令/循环 (IPC)。 现代服务器可以执行多达4个IPC,用于强大的计算绑定工作负载。 您希望尽可...

限制C ++中的CPU使用率(Limit CPU Usage in C++)

使用getrusage() ,请参阅Linux命令以检测程序的计算机资源使用情况 当你检查,并且你已经使用了你想要的毫秒运行时间时,使用nanosleep()来休眠几毫秒。 调整百分比以符合您的要求。 Use getrusage(), see Linux commands to detect the computer resource usage of a program And when you check, and you've used however many milliseconds o...

限制SqlBulkCopy的CPU(Limit CPU at SqlBulkCopy)

您正在更新的数据是否会影响其他计算机查询的结果? 如果它然后它应该阻止它们,与CPU无关,但因为记录被锁定以进行更新。 您希望操作尽可能快地运行,因此最大CPU是好的。 如果这两个数据集不同,那么没有理由为配置良好的SQL服务器无法同时服务这两个数据集,请查看调优选项,可用内存量等 Is the data you're updating affecting the results of the other machine's queries? If it is then it should blo...

是否有任何限制mongodb CPU使用?(Is there anything to limit mongodb cpu usage?)

你很可能缺少索引; 请确保查看PHP教程的索引部分。 You most likely are missing indexes; make sure you review the indexing section of the PHP tutorial.

限制Windows .NET服务的CPU使用率(Limit the cpu usage of a windows .NET service)

这些天的内存带宽和处理器缓存的使用与问题的匹配是CPU时间。 我不知道一个跟不上的操作系统...... 您可以尝试使用Thread.Sleep睡眠时间的50%,凌乱但可能有效。 These days’ memory band-width and usage of the processor cache is as match of a problem is CPU time. I don’t know of a OS that has kept up... You could try using ...

相关文章

更多

java线程状态详解(6种)

java线程类为:java.lang.Thread,其实现java.lang.Runnable接口。 ...

Java 多线程编程

Java 多线程编程 Java给多线程编程提供了内置的支持。一个多线程程序包含两个或多个能并发 ...

请教多线程JAVA问题

需求: 命令队列(存放n个命令,ip 端口 命令ID等信息),通过多线程scoket(线程数是20个 ...

求推荐JAVA 多线程编程书籍

求推荐JAVA 多线程编程书籍

Callable接口实现Java多线程

Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类 ...

一步一步掌握java的线程机制(一)----创建线程

现在将1年前写的有关线程的文章再重新看了一遍,发现过去的自己还是照本宣科,毕竟是刚学java的人,就想 ...

在main方法中开启线程与@Test中开启线程

用来测试线程同步问题的代码: public class SynchronizeDemo { p ...

java上传

java上传 代码 例子 项目开发 !!!

Java 简介

Java 简介 Java是由Sun Microsystems公司于1995年5月推出的Java面向对 ...

Java 异常处理

Java 异常处理 异常是程序中的一些错误,但并不是所有的错误都是异常,并且错误有时候是可以避免 ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本