Home  >  Q&A  >  body text

java - 异步情况下的循环,怎么解决这个问题

PHPzPHPz2719 days ago446

reply all(6)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:10:52

    Use synchronizedkeywords

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 10:10:52

    Add volatile keyword to list

    reply
    0
  • 阿神

    阿神2017-04-18 10:10:52

    I just watched the practical concurrent programming today about the safe release and access of mutable objects:
    Secure release:

    1. Initialize an object reference in a static initialization function;

    2. Save the reference of the object on volatile or AtomicReference

    3. Save the reference of the object to a final type that correctly constructs the object

    4. Save objects within the scope of a lock.

    Secure Access:

    1. Thread closed

    2. Read-only sharing

    3. Thread-safe sharing, the internal access method of the published object is thread-safe, and no external synchronization is required

    4. Protect objects, publish mutable objects by restricting external access, and specify the interface for accessing mutable objects.

    static List<String> arrayList = new ArrayList<>();This has complied with the first rule of safe publishing
    Then we must ensure safe access. Since the list must not be safely accessed in the first three situations, we can only rely on restricting external access when publishing objects, that is, adding Lock.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:10:52

    It can be realized according to the request of the subject, but the realization of this demand is very strange.

        private static void test1(final int i) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (arrayList) {
                    while (arrayList.size() != i) {
                        try {
                            arrayList.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    arrayList.add(i, i + "position");
                    arrayList.notifyAll();
                }
            }
        }).start();
    }
    

    In addition to this method, it can also be achieved through join和传入countdownlatch. If you really want to be like the subject, it is better not to use multi-threading

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:10:52

    Use the invokeAll method of the thread pool to ensure that the order of the results is consistent with the order of the parameters passed in

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:10:52

    public static void main(String[] args) {
            ExecutorService exec = Executors.newFixedThreadPool(10);
            
            List<Callable<Integer>> list = new ArrayList<>();
            
            for (int i = 0; i < 10; i++) {
                list.add(newTask(i));
            }
            
            try {
                for (Future<Integer> future : exec.invokeAll(list)) {
                    try {
                        System.out.println(future.get());
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            exec.shutdown();
        }
        
        static Callable<Integer> newTask(final int t) {
            return new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    System.out.println("newTask: " + t);
                    try {
                        Thread.sleep((10 - t) * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return t;
                }
            }
        }

    reply
    0
  • Cancelreply