English 中文(简体)
Java - 基础多读
原标题:Java - Basic Multithreading
  • 时间:2011-11-08 20:15:55
  •  标签:
  • java

我要问一下有关 Java线的基本问题。 让我们考虑一种生产者——消费者的设想。 只有一个生产商,只有一家消费者。 消费者随意到达,一旦服务于他们,即意味着每个消费者都自行行驶。 我是否仍然为消费者使用永远条件?

public class Consumer extends Thread {
    public void run() {
        while (true) {
        }
    }
}

t不停地步行?

问题回答

我要说的是,我可以执行。

如果你想永远走下去,我会永远走下去。

共同的替代办法是使用

while(!Thread.currentThread().isInterrupted()) {

while(!Thread.interrupted()) {

因此,你可能希望做这样的事情。

while(beingServed)
{
    //check if the customer is done being served (set beingServed to false)
}

这样一来,如果你想要死亡,就会越狱。

为什么不使用代表消费者存在的<条码>boolean?

public class Consumer extends Thread {
    private volatile boolean present;

    public Consumer() {
        present = true;
    }

    public void run() {
        while (present) {
            // Do Stuff
        }
    }

    public void consumerLeft() {
        present = false;
    }
}

First, you can create for each consumer and after the consumer will finish it s job than the consumer will finish the run function and will die, so no need for infinite loop. however, creating thread for each consumer is not good idea since creation of thread is quite expensive in performance point of view. threads are very expensive resources. In addition, i agree with the answers above that it is better to implement runnable and not to extends thread. extend thread only when you wish to customize your thread. I strongly suggest you will use thread pool and the consumer will be the runnable object that ran by the thread in the thread pool. the code should look like this:

public class ConsumerMgr{

 int poolSize = 2;

int maxPoolSize = 2;

long keepAliveTime = 10;

ThreadPoolExecutor threadPool = null;

final ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(
        5);

public ConsumerMgr()
{
    threadPool = new ThreadPoolExecutor(poolSize, maxPoolSize,
            keepAliveTime, TimeUnit.SECONDS, queue);

}

public void runTask(Runnable task)
{
    // System.out.println("Task count.."+threadPool.getTaskCount() );
    // System.out.println("Queue Size before assigning the
    // task.."+queue.size() );
    threadPool.execute(task);
    // System.out.println("Queue Size after assigning the
    // task.."+queue.size() );
    // System.out.println("Pool Size after assigning the
    // task.."+threadPool.getActiveCount() );
    // System.out.println("Task count.."+threadPool.getTaskCount() );
    System.out.println("Task count.." + queue.size());

}

http://em>extend不是一个好的想法。 read(除非你正在穿上一种新型的read子——永远不会穿透)。

最好的办法是将Runnable传送给Thread s Constructionor。

public class Consumer implements Runnable {

    public void run() {
        while (true) {
            // Do something
        }
    }
}

new Thread(new Consumer()).start();

一般而言,while(true) 是科索沃,但你必须处理由于正常wake或伪造的催交而中断的问题。 该网站有许多例子。

页: 1 Java Concurrency in Practice。

对于生产者消费模式,你最好使用等待()和通知()。 见tutorial 。 这比在(真实)休息期间更有成效。

If you want your thread to processes messages until you kill them (or they are killed in some way) inside while (true) there would be some synchronized call to your producer thread (or SynchronizedQueue, or queuing system) which would block until a message becomes available. Once a message is consumed, the loop restarts and waits again.

If you want to manually instantiate a bunch of thread which pull a message from a producer just once then die, don t use while (true).





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签