java 启动线程后,我们如何保持运行功能运行?我有很多想法,但我不确定哪个更专业?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12935364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
After starting a thread how could we keep the run function running? I have bunch of ideas but I'm not sure which is more professional?
提问by Bernard
In a Thread
After calling the start()
as you know it will call the run()
function in the Runnable
class. In the run()
function I want the thread stays as long as it receive the "Bye" message from the client. If i put them in the while loop it takes heaps of memory i think and I'm not using the power of thread. By the way i don't want my thread sleep in the run function by calling Thread.sleep(6000);
Is there any other way to stay there in the run function?
在Thread
调用之后start()
,你知道它将调用类中的run()
函数Runnable
。在run()
函数中,只要线程从客户端接收到“再见”消息,我就希望它一直保持下去。如果我将它们放在 while 循环中,我认为它会占用大量内存,而且我没有使用线程的功能。顺便说一句,我不希望我的线程通过调用在 run 函数中休眠Thread.sleep(6000);
有没有其他方法可以留在 run 函数中?
If the answer is join where and how and use it? Should I pop it at the beginning of the run function and it stays there until I send the "Bye" from client?
Should I say
while((request=in.readLine())!=null){
? It did not work because I think it will lose the connection with the client or better say client losing the connection?Should I say
while(Thread.isAlive)
and then kill the threat when I receive the "Bye" by callingThread.stop
which is little bit dangerous?
如果答案是加入在哪里以及如何使用它?我应该在运行函数的开头弹出它并保持在那里直到我从客户端发送“Bye”?
我应该说
while((request=in.readLine())!=null){
吗?它没有用,因为我认为它会失去与客户端的连接,或者最好说客户端失去连接?while(Thread.isAlive)
当我通过呼叫收到“再见”时,我是否应该说然后杀死威胁,Thread.stop
这有点危险?
Here is my simplified code:
这是我的简化代码:
while(true)
{
ClientWorker w;
try
{
w = new ClientWorker(serverSocket.accept());
Thread t = new Thread(w);
t.start();
}
...... }
class ClientWorker implements Runnable {
public ClientWorker(Socket incoming)
{
myList = my;
this.incoming = incoming;
}
public synchronized void run()
{
in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
.
.
..
...
}
回答by Adriaan Koster
In the simplest case just let your run method do its work and terminate when appropriate, something like this:
在最简单的情况下,让你的 run 方法完成它的工作并在适当的时候终止,就像这样:
public void run() {
boolean running = true;
while(running) {
running = doWork();
if (Thread.interrupted()) {
return;
}
}
}
Here the process stops when the doWork() method returns false. It is also good style to allow your thread to be interrupted, especially if it needs to run for a long time, see this tutorial. For any of this to work, doWork() should return regularly. Note you cannot restart threads, once the run method has returned the thread is reclaimed by the system.
当 doWork() 方法返回 false 时,此过程停止。允许你的线程被中断也是一种很好的风格,特别是如果它需要运行很长时间,请参阅本教程。要使其中的任何一项工作, doWork() 应该定期返回。请注意,您无法重新启动线程,一旦 run 方法返回,系统就会回收该线程。
If you need more control over your threads you could create separate Worker and ThreadManager classes.
如果您需要对线程进行更多控制,您可以创建单独的 Worker 和 ThreadManager 类。
To let the ThreadManager terminate the Worker, create a volatile boolean field in your Worker which is checked periodically:
要让 ThreadManager 终止 Worker,请在定期检查的 Worker 中创建一个 volatile 布尔字段:
public class Worker extends Thread {
private volatile boolean running;
public void run() {
running = true;
while(running) {
running = doWork();
if (Thread.interrupted()) {
return;
}
}
}
public void stopRunning() {
running = false;
}
}
The Worker ends when interrupted or when the work is completed. Also the ThreadManager can request the Worker to stop by invoking the stopRunning() method.
Worker 在中断或工作完成时结束。ThreadManager 也可以通过调用 stopRunning() 方法请求 Worker 停止。
If your thread runs out of work it could also call the wait() method on the ThreadManager. This pauses the thread until it is notified that there is new work to do. The ThreadManager should call notify() or notifyAll() when new work arrives (ThreadManager is used as a monitor in this example).
如果您的线程没有工作,它还可以调用 ThreadManager 上的 wait() 方法。这会暂停线程,直到通知有新工作要做。当新工作到达时,ThreadManager 应该调用 notify() 或 notifyAll() (在这个例子中 ThreadManager 用作监视器)。
With this approach you can keep the Worker simple and only concerned with doing the work. The ThreadManager determines the number of threads and makes work available to them but does not need to know details of the actual work. One step further would be to split out 'work' into a separate class too, which you could call Job. An example of this can be found in my webcrawler example. This could be useful for passing new work from the ThreadManager to the worker thread.
通过这种方法,您可以使 Worker 保持简单,并且只关心完成工作。ThreadManager 确定线程的数量并为它们提供工作,但不需要知道实际工作的详细信息。更进一步的做法是将“工作”也拆分为一个单独的类,您可以将其称为 Job。这方面的一个例子可以在我的webcrawler 示例中找到。这对于将新工作从 ThreadManager 传递给工作线程很有用。
EDIT: clarification: If the thread doesn't do any work and just needs to wait for some condition, don't use an iteration to wait, but use either wait/notify (see the webcrawler example I gave) or a simple callback when the condition arises.
编辑:澄清:如果线程不做任何工作而只需要等待某个条件,不要使用迭代来等待,而是使用等待/通知(参见我给出的网络爬虫示例)或一个简单的回调条件出现。
回答by Riptyde4
I know this is late, but this is a much better implementation and avoids heavy CPU usage by busy waiting - Allows context switching when the thread is waiting for a signal.
我知道这已经晚了,但这是一个更好的实现,并且通过忙等待避免了大量 CPU 使用 - 在线程等待信号时允许上下文切换。
Setting the semaphore to a value of 0 ensures that when the thread attempts to acquire permission to continue, it does not get it and waits. When you release the semaphore, the count is increased by 1, allowing the thread to continue and the count is decreased back to 0.
将信号量设置为值 0 可确保当线程尝试获取继续权限时,它不会获取并等待。当您释放信号量时,计数增加 1,允许线程继续,计数减少回 0。
In main:
在主要:
Semaphore sem = new Semaphore(0);
Worker t = new Worker(sem);
t.start();'
// The thread is now running but waiting, signal the semaphore to start work
sem.release();
The Thread
线程
public class Worker(Semaphore sem) extends Thread {
public void run() {
sem.acquire();
doWork();
}
}
回答by taufique
just return
from the run()
when you get "bye"
就return
从run()
你得到"bye"