Home > Software engineering >  Run the function in thread(Multi-Thread)
Run the function in thread(Multi-Thread)

Time:11-10

I am running a function with string similarity to find the similarity of the strings in the list. But I want to do this in a synchronized way by using multi threads in this list.

Each thread does the whole task by itself. I want to do the task once, with multiple thread

 public class Runn implements Runnable {
 public void run() {

      synchronized (LOCK){
          
          newList=listExe.getStringList();
          try {

              int i=1;
              for (String s: newList) {
                  //System.out.println(s);
                  //System.out.println(newList.get(i));
                  System.out.println("Similarity "  solution.findSimilarityRatio(s,newList.get(i)));
                  System.out.println(Thread.currentThread().getName());
                  System.out.println();
                  i  ;
                  if(i==newList.size()){
                      break;
                  }

              }
              Thread.sleep(200);
          }
          catch (Exception e){
              e.printStackTrace();
              System.out.println(e.getMessage());
          }
          
      }
      
    }
 }

public static void main(String[] args) {


   Runn runnable=new Runn();
        ExecutorService pool= Executors.newFixedThreadPool(10);

        for (int i=0;i<10;i  ){


            pool.execute(runnable);
        }
        }

CodePudding user response:

I'd do something like the following. You submit one Runnable per string in the list. Then your 10 threads will work in parallel to find the similarity of that one string against all of the elements in the list. This is a typical pattern of how to use the Java thread-pools.

public static void main(String[] args) {
    ExecutorService pool = Executors.newFixedThreadPool(10);
    List<String> stringList = listExe.getStringList();
    for (String str : stringList) {
        pool.submit(new SimilarityRunnable(str, stringList));
    }
    // after we submit the last job to the pool we should shut it down
    pool.shutdown();
}

private static class SimilarityRunnable implements Runnable {
    private final String str;
    private final List<String> stringList;

    public SimilarityRunnable(String str, List<String> stringList) {
        this.str = str;
        this.stringList = stringList;
    }

    public void run() {
        for (String listStr : stringList) {
            // we deliberately use == here to skip the same list element
            if (listStr == str) {
                continue;
            }
            // if solution object is not reentrant, synchronize on it here
            System.out.println(Thread.currentThread().getName()
                  ": similarity of "   str   " to "   listStr   " is "
                  solution.findSimilarityRatio(str, listStr));
        }
    }
}

CodePudding user response:

public static void main(String[]args){
    final ConcurrentLinkedQueue<String> queue=new ConcurrentLinkedQueue<>();
    // fill the queue
    // ...

    final String s = ...; //

    Runnable runnable=()->{
        try {
          for (String i =queue.poll(); i != null; i=queue.poll()) {
            System.out.println("Similarity "   solution.findSimilarityRatio(s, i));
            System.out.println(Thread.currentThread().getName());
            System.out.println();
          }
        } catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    };
    
    ExecutorService pool=Executors.newFixedThreadPool(10);

    for(int i=0;i<10;i  ){
        pool.execute(runnable);
    }
}

  • Related