Help me figure out a lot of things.



  • I'm squeezing a lot of sweat, trying to fill out the sheets in parallel, and then I'll take it to the console.
    And as far as I understand, jvm starts flow depending on the moon's phase, and the method pulls off other flows until the method works.
    And by joining the two streams, do we have a steady performance rather than a parallel one? ?
    How do you fill the sheet in parallel and put it at the end in the console?

    public class Solution {
        static List<Integer> list1 = new ArrayList<>();
        static List<Integer> list2 = new ArrayList<>();
    
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -&gt; {
            for (int i = 0; i &lt; 100; i++) {
                list1.add(i);
            }
        });
    
        Thread thread2 = new Thread(() -&gt; {
            for (int i = 99; i &gt;= 0; i--) {
                list2.add(i);
            }
        });
    
        thread1.start();
    

    // thread1.join();

        thread2.start();
    

    // thread2.join();

        printList(list1);
        printList(list2);
    }
    
    static void printList(List&lt;Integer&gt; list) {
        for (Integer integer : list) {
            System.out.print(integer);
        }
        System.out.println();
    }
    

    }



  • That's how it works.

    public class Solution {
        static List<Integer> list = new ArrayList<>();
    
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -&gt; {
            for (int i = 0; i &lt; 100; i++) {
                synchronized(list) {
                    list.add(i);
                }
            }
        });
    
        Thread thread2 = new Thread(() -&gt; {
            for (int i = 99; i &gt;= 0; i--) {
                synchronized(list) {
                    list.add(i);
                }
            }
        });
    
        thread1.start();
        thread2.start();
        thread2.join();
        thread1.join();
    
        printList(list);
    }
    
    static void printList(List&lt;Integer&gt; list) {
        for (Integer integer : list) {
            System.out.println(integer);
        }
        System.out.println();
    }
    

    }

    Pay attention to synchronizing access to the list.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2