Java 线程:实时应用示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32332033/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:02:02  来源:igfitidea点击:

Java Thread: Real Time Application Example

javamultithreading

提问by Fulcum

I was asked a question in an interview, where i have list available in the main method and and i was told there is some operation to be performed on each item in the list, how would i achieve this using threads concept. Consider the following scenario: I have a list of integers. I need to print all the values from the list. Can it be done using threads concept where i have multiple threads running on each item in the list and where each thread is used to print out a value rather than one thread printing all the values? I am not trying to modify any value in the list.

我在一次采访中被问到一个问题,我在 main 方法中有可用的列表,并且我被告知要对列表中的每个项目执行一些操作,我将如何使用线程概念来实现这一点。考虑以下场景:我有一个整数列表。我需要打印列表中的所有值。是否可以使用线程概念来完成,其中我有多个线程在列表中的每个项目上运行,并且每个线程用于打印一个值而不是一个线程打印所有值?我不想修改列表中的任何值。

回答by Houssem Badri

I hope you are looking for something like that:

我希望你正在寻找这样的东西:

public class MaltiThreadExample {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));

        for (int i : list) {
            Thread th = new Thread() {
                @Override
                public void run() {
                    System.out.println(i);
                }
            };
            th.start();
        }
    }

}

The output is for one execution:

输出用于一次执行:

run:
3
1
2
BUILD SUCCESSFUL (total time: 0 seconds)

回答by Little Santi

Yes, it is a typical producer-consumerparadigm:

是的,这是一个典型的生产者-消费者范式:

Imagine a Runnable class who receives an Iterator as parameter, and waits over a certain monitor, and then consumes one item from the iterator, and last notifies the same monitor. Loops while the iterator has more items.

想象一个 Runnable 类,它接收一个 Iterator 作为参数,并等待某个监视器,然后从迭代器中消费一个项目,最后通知同一个监视器。当迭代器有更多项时循环。

Upon this, it will be enough to create the list of numbers, create the consumer threads passing them the list's iterator, and start them.

在此基础上,创建数字列表、创建将列表的迭代器传递给它们的消费者线程并启动它们就足够了。

回答by Oli

The code below is not tested at all. It's just something that comes into mind. The last implementation using parallelStream() might be what you are looking for.

下面的代码根本没有经过测试。这只是想到的东西。使用 parallelStream() 的最后一个实现可能就是您正在寻找的。

public class DemoApplication {

    public static void main(String[] args) {
        final List<Integer> myIntegerList = Arrays.asList(1, 2, 3);

        // Good old for-each-loop
        for (Integer item : myIntegerList) {
            System.out.print(item);
        }

        // Java 8 forEach with Consumer
        final Consumer<Integer> consumer = new Consumer<Integer>() {
            @Override
            public void accept(Integer item) {
                System.out.print(item);
            }
        };

        myIntegerList.forEach(consumer);

        // Java 8 forEach with Lambda
        myIntegerList.forEach((item) -> System.out.print(item));

        // Java 8 forEach on parallelStream with Lambda
        myIntegerList.parallelStream().forEach((item) -> System.out.print(item));
    }
}

回答by Solomon Slow

i am trying to understand the advantage of threads.

我试图了解线程的优势。

There are basically two reasons for using multiple threads in a program:

在程序中使用多线程基本上有两个原因:

(1) Asynchronous event handling:Imagine a program that must wait for and respond to several different kinds of input, and each kind of input can happen at completely arbitrary times.

(1) 异步事件处理:想象一个程序必须等待和响应几种不同类型的输入,而每种输入都可以在完全任意的时间发生。

Before threads, we used to write a big event loop, that would pollfor each different kind of event, and then dispatchto different handlerfunctions. Things could start to get ugly when one or more of the event handlers was stateful(i.e., what it did next would depend on the history of previous events.)

在线程之前,我们曾经编写一个大事件循环,它会轮询每种不同类型的事件,然后分派到不同的处理函数。当一个或多个事件处理程序处于有状态时,事情可能会开始变得丑陋(即,它接下来所做的将取决于之前事件的历史记录。)

A program that has one thread for each different kind of event often is much cleaner. That is to say, it's easier to understand, easier to modify, etc. Each thread loops waiting for just one kind of event, and its state (if any) can be kept in local variables, or its state can be implicit (i.e., depends on what function the thread is in at any given time).

对于每种不同类型的事件都有一个线程的程序通常要干净得多。也就是说,它更容易理解,更容易修改等等。每个线程循环只等待一种事件,它的状态(如果有)可以保存在局部变量中,或者它的状态可以是隐式的(即,取决于线程在任何给定时间所处的功能)。

(2) Multiprocessing(a.k.a., "parallel processing", "concurrent programming",...): Using worker threadsto perform background computationsprobably is the most widespread model of multiprocessing in use at this moment in time.

( 2) 多处理(又名,“并行处理”,“并发编程”,...):使用工作线程执行后台计算可能是目前使用最广泛的多处理模型。

Multithreading is the lowest-level of all multiprocessing models which means (a) it is the hardest to understand, but (b) it is the most versatile.

多线程是所有多处理模型中最底层的,这意味着 (a) 它是最难理解的,但 (b) 它是最通用的。