简体   繁体   English

多线程|| 爪哇

[英]Multithreading || Java

I've a program that's as follows below. 我有一个程序,如下所示。 I want three concurrent threads to add different Strings to infiList ("This", "is", "infinite") using thread synchronization. 我希望三个并发线程使用线程同步将不同的字符串添加到infiList (“ This”,“ is”,“ infinite”)中。

I want to append certain threads also, for example; 例如,我还要附加某些线程。

  • If the last word in infiList is currently “This”, the thread should append word “is” to infiList . 如果infiList的最后一个单词当前为“ This”,则线程应将单词“ is”附加到infiList

  • If the last word in infiList is currently “is”, the thread should append word “infinite” to infiList . 如果在最后一个字infiList目前是“是”,该线程应该追加词“无限”来infiList

  • If the last word in infiList is currently “infinite”, or if infiList is still empty, the thread should append word “This” to infiList . 如果infiList的最后一个单词当前为“无限”,或者infiList仍然为空,则线程应在infiList附加单词“ This”。

  • At any time, infiList should contain “This” only at the beginning of the list or directly after an occurrence of “infinite”, “is” should occur in the list only directly after a “This”, and an “infinite” should occur only directly after an “is”. 任何时候, infiList都应仅在列表的开头或infiList出现“ infinite”之后才包含“ This”,“ is”应仅在“ This”之后直接出现在列表中,而“ infinite”应出现在列表中仅在“是”之后。

Any help as to how to do this is appreciated. 感谢您提供有关如何执行此操作的任何帮助。

import java.util.ArrayList;

public class Multithreading implements Runnable {

public static ArrayList<String> infiList = new ArrayList<>();

@Override
public void run() {
    for (int i=0; i<100; i++) {
        String s = null;
        synchronized (infiList) {
            if(infiList.isEmpty())
                infiList.add("This");
            else
            {
                s = infiList.get(infiList.size()-1);

            if(s.equals("This"))
                infiList.add("is");
            else if(s.equals("is"))
                infiList.add("infinite");
            else if(s.equals("infinite"))
                infiList.add("This");
            }
        }
    }
}

public static void main (String args[]) {
    // Create three concurrent threads
    new Thread(new Multithreading()).start();
    new Thread(new Multithreading()).start();
    new Thread(new Multithreading()).start();

}
}

Very naive quick fix for the problem. 对这个问题非常幼稚的快速修复。 Synchronized will obtain a lock, on the arraylist, check the element and insert it based on your rules. 同步将获得一个锁定,在arraylist上,根据您的规则检查元素并将其插入。 But due to your logic being depending on the last element while adding a element to the array while maintaning the order of the elements this is actually not multithreaded but a sequential program. 但是由于您的逻辑依赖于最后一个元素,同时在维护元素顺序时将元素添加到数组中,因此这实际上不是多线程的,而是顺序程序。

This is simply because, when multithreaded programs run, you don't care abount the sequentioning, because you can never guarentee it. 这仅仅是因为,当运行多线程程序时,您不必在意序列化,因为您永远无法保证它。 In most cases you will go into a Divide and Conqueer style algorithm, where the algorithm will be split up into pieces and calculated in pieces. 在大多数情况下,您将使用分而治之风格的算法,该算法将分为几部分并进行计算。

@Override
public void run() {
    for(int i = 0; i < 100; i++) {
        String s = null;
        synchronized (infiList) {
            if(infiList.isEmpty())
                infiList.add("This");
            else
            {
                s = infiList.get(infiList.size()-1);

            if(s.equals("This"))
                infiList.add("is");
            else if(s.equals("is"))
                infiList.add("infinite");
            else if(s.equals("infinite"))
                infiList.add("This");
            }
        }
    }
}

How to utilize multithreading 如何利用多线程

If we look at your example in another case, where you needed to calculate something before you put it into the array. 如果我们在另一种情况下查看您的示例,则需要先计算一些内容,然后再将其放入数组。 This could lead to utilzing the multithreading performance better. 这可能导致更好地利用多线程性能。

@Override
public void run() {
    while (true) {
        String s = null;

        CalculateSomethingBig();

        synchronized (infiList) {
            ...
        }
    }
}

If we play with the thought, that the primary runtime lies within CalculateSomethingBig() , this will now utilize more of the computers multitasking capabilities, because more of the threads will use time to calculate and utilize processing power then to wait on a lock being released. 如果我们想到,主运行时位于CalculateSomethingBig() ,那么它将利用更多的计算机多任务处理功能,因为更多的线程将花费时间计算和利用处理能力,然后等待释放锁。

How to get output 如何获得输出

    public static void main(String args[]) {
    // Create three concurrent threads
    new Thread(new Multithreading()).start();
    new Thread(new Multithreading()).start();
    new Thread(new Multithreading()).start();

    for(String s : infiList)
        System.out.println(s);
}

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

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