Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

Java Gold 例題集 並列処理

Posted at

問 1

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(3);
        Future<Integer> future1 = executor.submit(() -> 1 + 2);
        Future<Integer> future2 = executor.submit(() -> 2 + 3);
        Future<Integer> future3 = executor.submit(() -> 3 + 4);

        System.out.println(future1.get());
        System.out.println(future2.get());
        System.out.println(future3.get());

        executor.shutdown();
    }
}
解答

3
5
7
3つのタスクを並列に実行し、結果を取得しています。それぞれのタスクは異なるスレッドで実行され、結果を順に取得しています。

問 2

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        Future<Integer> future1 = executor.submit(() -> 5 * 2);
        Future<Integer> future2 = executor.submit(() -> 6 / 2);
        Future<Integer> future3 = executor.submit(() -> 7 - 2);

        System.out.println(future1.get());
        System.out.println(future2.get());
        System.out.println(future3.get());

        executor.shutdown();
    }
}
解答

10
3
5
2つのスレッドプールで3つのタスクを処理しています。最初の2つのタスクが並列に実行され、最後のタスクはそれらが完了した後に実行されます。

問 3

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(1);
        Future<Integer> future1 = executor.submit(() -> 10 - 4);
        Future<Integer> future2 = executor.submit(() -> 2 * 3);

        System.out.println(future1.get());
        System.out.println(future2.get());

        executor.shutdown();
    }
}
解答

6
6
単一スレッドプールを使用しているため、タスクは順次実行されます。

問 4

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(3);
        AtomicInteger count = new AtomicInteger(0);

        for (int i = 0; i < 5; i++) {
            executor.submit(() -> {
                System.out.println(count.incrementAndGet());
            });
        }

        executor.shutdown();
    }
}
解答

1
2
3
4
5
AtomicIntegerを使用しているため、排他制御が働き、正しくインクリメントされます。

問 5

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        scheduler.schedule(() -> System.out.println("Hello, World!"), 2, TimeUnit.SECONDS);

        scheduler.shutdown();
    }
}
解答

Hello, World!
2秒後に"Hello, World!"が出力されます。ScheduledExecutorServiceを使用した遅延タスクの例です。

問 6

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newCachedThreadPool();
        AtomicInteger sum = new AtomicInteger(0);

        Future<?> future1 = executor.submit(() -> sum.addAndGet(10));
        Future<?> future2 = executor.submit(() -> sum.addAndGet(20));

        future1.get();
        future2.get();

        System.out.println(sum);

        executor.shutdown();
    }
}
解答

30
並列処理により、複数のスレッドで安全にAtomicIntegerの値が更新されています。

問 7

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        Future<String> future1 = executor.submit(() -> "Task 1");
        Future<String> future2 = executor.submit(() -> "Task 2");

        System.out.println(future1.get());
        System.out.println(future2.get());

        executor.shutdown();
    }
}
解答

Task 1
Task 2
並列にタスクを実行し、それぞれの結果を取得しています。

問 8

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(3);
        AtomicInteger count = new AtomicInteger(0);

        for (int i = 0; i < 3; i++) {
            executor.submit(() -> {
                count.addAndGet(5);
                System.out.println(count.get());
            });
        }

        executor.shutdown();
    }
}
解答

5
10
15
3つのタスクが並列に実行され、それぞれ5ずつインクリメントされています。

問 9

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        Future<Integer> future1 = executor.submit(() -> 8 + 2);
        Future<Integer> future2 = executor.submit(() -> 4 * 2);

        System.out.println(future1.get());
        System.out.println(future2.get());

        executor.shutdown();
    }
}
解答

10
8
2つのタスクを並列に実行し、結果を取得しています。

問 10

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(1);

        Future<Integer> future1 = executor.submit(() -> 3 + 4);
        Future<Integer> future2 = executor.submit(() -> 10 - 6);

        System.out.println(future1.get());
        System.out.println(future2.get());

        executor.shutdown();
    }
}
解答

7
4
単一スレッドプールでタスクが順次実行されます。

問 11

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(3);

        Future<String> future1 = executor.submit(() -> "Hello");
        Future<String> future2 = executor.submit(() -> "World");

        System.out.println(future1.get() + " " + future2.get());

        executor.shutdown();
    }
}
解答

Hello World
2つのタスクを並列に実行し、結果を組み合わせています。

問 12

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        AtomicInteger sum = new AtomicInteger(0);

        Future<?> future1 = executor.submit(() -> sum.addAndGet(15));
        Future<?> future2 = executor.submit(() -> sum.addAndGet(25));

        future1.get();
        future2.get();

        System.out.println(sum);

        executor.shutdown();
    }
}
解答

40
AtomicIntegerを使用してスレッド間で共有される変数の値が安全に更新されています。

問 13

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        scheduler.scheduleAtFixedRate(()

 -> System.out.println("Tick"), 1, 2, TimeUnit.SECONDS);

        Thread.sleep(5000);

        scheduler.shutdown();
    }
}
解答

Tick
Tick
Tick
1秒後に開始し、その後2秒ごとに「Tick」が出力されるタスクを実行しています。

問 14

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newCachedThreadPool();

        Future<?> future1 = executor.submit(() -> System.out.println("Task 1"));
        Future<?> future2 = executor.submit(() -> System.out.println("Task 2"));

        future1.get();
        future2.get();

        executor.shutdown();
    }
}
解答

Task 1
Task 2
タスクが並列に実行され、それぞれの結果が出力されます。

問 15

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(4);
        AtomicInteger total = new AtomicInteger(0);

        for (int i = 0; i < 4; i++) {
            executor.submit(() -> {
                total.addAndGet(10);
                System.out.println(total.get());
            });
        }

        executor.shutdown();
    }
}
解答

10
20
30
40
4つのタスクが並列に実行され、AtomicIntegerの値が正しくインクリメントされています。

問 16

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newSingleThreadExecutor();

        Future<String> future = executor.submit(() -> "Single Thread");

        System.out.println(future.get());

        executor.shutdown();
    }
}
解答

Single Thread
シングルスレッドエグゼキュータでタスクが実行され、その結果が出力されます。

問 17

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(3);

        executor.submit(() -> System.out.println("Task A"));
        executor.submit(() -> System.out.println("Task B"));
        executor.submit(() -> System.out.println("Task C"));

        executor.shutdown();
    }
}
解答

Task A
Task B
Task C
3つのタスクが並列に実行され、それぞれの結果が出力されます。

問 18

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);

        scheduler.scheduleWithFixedDelay(() -> System.out.println("Delay Task"), 1, 3, TimeUnit.SECONDS);

        Thread.sleep(10000);

        scheduler.shutdown();
    }
}
解答

Delay Task
Delay Task
Delay Task
最初のタスクが1秒後に開始し、その後3秒ごとに「Delay Task」が出力されます。

問 19

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        executor.submit(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Task 1: " + i);
                try { Thread.sleep(100); } catch (InterruptedException e) { }
            }
        });

        executor.submit(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Task 2: " + i);
                try { Thread.sleep(100); } catch (InterruptedException e) { }
            }
        });

        executor.shutdown();
    }
}
解答

Task 1: 0
Task 2: 0
Task 1: 1
Task 2: 1
Task 1: 2
Task 2: 2
Task 1: 3
Task 2: 3
Task 1: 4
Task 2: 4
2つのタスクが並列に実行され、それぞれの出力が交互に表示されます。

問 20

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        Future<?> future1 = executor.submit(() -> System.out.println("Task A"));
        Future<?> future2 = executor.submit(() -> System.out.println("Task B"));

        future1.get();
        future2.get();

        executor.shutdown();
    }
}
解答

Task A
Task B
タスクが並列に実行され、結果が順次出力されます。

問 21

import java.util.concurrent.*;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(4);
        CountDownLatch latch = new CountDownLatch(4);

        IntStream.range(0, 4).forEach(i -> executor.submit(() -> {
            System.out.println("Task " + i);
            latch.countDown();
        }));

        try {
            latch.await();
            System.out.println("All tasks completed");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }
    }
}
解答

Task 0
Task 1
Task 2
Task 3
All tasks completed
4つのタスクが並列に実行され、全てのタスクが完了した後に「All tasks completed」が出力されます。

問 22

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        AtomicInteger counter = new AtomicInteger();

        Runnable task = () -> {
            for (int i = 0; i < 5; i++) {
                System.out.println(counter.incrementAndGet());
            }
        };

        executor.submit(task);
        executor.submit(task);

        executor.shutdown();
    }
}
解答

1
2
3
4
5
6
7
8
9
10
2つのタスクが並列に実行され、AtomicIntegerの値がインクリメントされて出力されます。

問 23

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        Callable<Integer> task = () -> {
            Thread.sleep(2000);
            return 42;
        };

        Future<Integer> future = executor.submit(task);

        System.out.println("Future result: " + future.get());

        executor.shutdown();
    }
}
解答

Future result: 42
2秒後に計算結果「42」が出力されます。

問 24

import java.util.concurrent.*;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        CountDownLatch latch = new CountDownLatch(5);
        IntStream.range(0, 5).forEach(i -> executor.submit(() -> {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Completed task " + i);
            latch.countDown();
        }));

        latch.await();
        System.out.println("All tasks completed");

        executor.shutdown();
    }
}
解答

Completed task 0
Completed task 1
Completed task 2
Completed task 3
Completed task 4
All tasks completed
全てのタスクが完了した後に「All tasks completed」が出力されます。

問 25

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(3);
        Semaphore semaphore = new Semaphore(2);

        Runnable task = () -> {
            try {
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName() + " acquired permit");
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName() + " released permit");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        for (int i = 0; i < 5; i++) {
            executor.submit(task);
        }

        executor.shutdown();
    }
}
解答

Thread-0 acquired permit
Thread-1 acquired permit
Thread-0 released permit
Thread-2 acquired permit
Thread-1 released permit
Thread-3 acquired permit
Thread-2 released permit
Thread-4 acquired permit
Thread-3 released permit
Thread-4 released permit
セマフォにより、2つのタスクが同時に実行され、各スレッドが順次リリースします。

問 26

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("Task 1 completed");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, executor);

        CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(2000);
                System.out.println("Task 2 completed");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, executor);

        CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(future1, future2);
        combinedFuture.join();

        System.out.println("All tasks completed");

        executor.shutdown();
    }
}
解答

Task 1 completed
Task 2 completed
All tasks completed
2つのタスクが並列に実行され、全てのタスクが完了した後に「All tasks completed」が出力されます。

問 27

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(() -> {
            System.out.println("Periodic task");
        }, 1, 3, TimeUnit.SECONDS);

        Thread.sleep(10000);
        future.cancel(false);
        scheduler.shutdown();
    }
}
解答

Periodic task
Periodic task
Periodic task
タスクが1秒後に開始し、その後3秒ごとに「Periodic task」が出力され、10秒後にキャンセルされます。

問 28

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 1;
        }, executor);

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 2;
        }, executor);

        CompletableFuture<Integer> resultFuture = future1.thenCombine(future2, Integer::sum);

        System.out.println("Result: " + resultFuture.get());

        executor.shutdown();
    }
}
解答

Result: 3
2つの非同期タスクの結果を合計して出力します。

問 29

import java.util.concurrent.*;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(4);
        CyclicBarrier barrier = new CyclicBarrier(4, () -> System.out.println("Barrier Reached"));

        IntStream.range(0, 4).forEach(i -> executor.submit(() -> {
            try {
                System.out.println("Task " + i + " is waiting at the barrier");
                barrier.await();
                System.out.println("Task " + i + " passed the barrier");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }));

        executor.shutdown();
    }
}
解答

Task 0 is waiting at the barrier
Task 1 is waiting at the barrier
Task 2 is waiting at the barrier
Task 3 is waiting at the barrier
Barrier Reached
Task 0 passed the barrier
Task 1 passed the barrier
Task 2 passed the barrier
Task 3 passed the barrier
4つのタスクがバリアで待機し、全てが揃うと「Barrier Reached」が出力され、その後タスクがバリアを通過します。

問 30

import java.util.concurrent.*;

public class Main {
    public static void main

(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(3);

        Semaphore semaphore = new Semaphore(1);

        Runnable task = () -> {
            try {
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName() + " acquired the semaphore");
                Thread.sleep(3000);
                System.out.println(Thread.currentThread().getName() + " released the semaphore");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        for (int i = 0; i < 5; i++) {
            executor.submit(task);
        }

        executor.shutdown();
    }
}
解答

Thread-0 acquired the semaphore
Thread-0 released the semaphore
Thread-1 acquired the semaphore
Thread-1 released the semaphore
Thread-2 acquired the semaphore
Thread-2 released the semaphore
Thread-3 acquired the semaphore
Thread-3 released the semaphore
Thread-4 acquired the semaphore
Thread-4 released the semaphore
セマフォによって、同時に1つのスレッドだけがセマフォを取得し、3秒後にリリースします。

問 31

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(4);

        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 5;
        }, executor);

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 10;
        }, executor);

        CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 15;
        }, executor);

        CompletableFuture<Integer> resultFuture = CompletableFuture.allOf(future1, future2, future3)
            .thenApply(v -> {
                try {
                    return future1.get() + future2.get() + future3.get();
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                    return null;
                }
            });

        System.out.println("Sum: " + resultFuture.get());

        executor.shutdown();
    }
}
解答

Sum: 30
3つの非同期タスクが並列に実行され、全ての結果が合計されて出力されます。

問 32

import java.util.concurrent.*;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(3);
        Phaser phaser = new Phaser(1);

        Runnable task = () -> {
            phaser.register();
            System.out.println(Thread.currentThread().getName() + " arrived at phase 1");
            phaser.arriveAndAwaitAdvance();
            System.out.println(Thread.currentThread().getName() + " completed phase 1");
            phaser.arriveAndDeregister();
        };

        IntStream.range(0, 6).forEach(i -> executor.submit(task));

        Thread.sleep(1000);
        System.out.println("Phase 1 completed");
        phaser.awaitAdvance(0);

        executor.shutdown();
    }
}
解答

Thread-0 arrived at phase 1
Thread-1 arrived at phase 1
Thread-2 arrived at phase 1
Thread-3 arrived at phase 1
Thread-4 arrived at phase 1
Thread-5 arrived at phase 1
Phase 1 completed
Thread-0 completed phase 1
Thread-1 completed phase 1
Thread-2 completed phase 1
Thread-3 completed phase 1
Thread-4 completed phase 1
Thread-5 completed phase 1
全てのタスクがフェーズ1で待機し、全てが完了するまでフェーズ1が待機します。

問 33

import java.util.concurrent.*;
import java.util.concurrent.locks.*;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        ReadWriteLock rwLock = lock.readWriteLock();

        ExecutorService executor = Executors.newFixedThreadPool(2);

        Runnable readTask = () -> {
            rwLock.readLock().lock();
            try {
                System.out.println(Thread.currentThread().getName() + " is reading");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                rwLock.readLock().unlock();
            }
        };

        Runnable writeTask = () -> {
            rwLock.writeLock().lock();
            try {
                System.out.println(Thread.currentThread().getName() + " is writing");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                rwLock.writeLock().unlock();
            }
        };

        executor.submit(readTask);
        executor.submit(writeTask);
        executor.submit(readTask);

        executor.shutdown();
    }
}
解答

Thread-0 is reading
Thread-1 is writing
Thread-2 is reading
リーダーとライターのロックが適切に取得され、リーダーはライターの処理が終わるまで待機します。

問 34

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newCachedThreadPool();
        AtomicInteger counter = new AtomicInteger();

        Callable<Void> task = () -> {
            System.out.println("Task " + counter.incrementAndGet() + " started");
            Thread.sleep(2000);
            System.out.println("Task " + counter.get() + " finished");
            return null;
        };

        for (int i = 0; i < 5; i++) {
            executor.submit(task);
        }

        executor.shutdown();
    }
}
解答

Task 1 started
Task 2 started
Task 3 started
Task 4 started
Task 5 started
Task 1 finished
Task 2 finished
Task 3 finished
Task 4 finished
Task 5 finished
5つのタスクが並列に実行され、それぞれのタスクが開始と終了のメッセージを出力します。

問 35

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newSingleThreadExecutor();

        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1500);
                return 1;
            } catch (InterruptedException e) {
                e.printStackTrace();
                return 0;
            }
        }, executor);

        CompletableFuture<Integer> combinedFuture = future.thenCompose(result ->
            CompletableFuture.supplyAsync(() -> result + 1, executor)
        );

        System.out.println("Result: " + combinedFuture.get());

        executor.shutdown();
    }
}
解答

Result: 2
最初のタスクの結果を次のタスクで利用し、最終結果を出力します。

問 36

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        Callable<String> task1 = () -> {
            Thread.sleep(2000);
            return "Task 1";
        };

        Callable<String> task2 = () -> {
            Thread.sleep(1000);
            return "Task 2";
        };

        Future<String> future1 = executor.submit(task1);
        Future<String> future2 = executor.submit(task2);

        try {
            System.out.println("Result of task1: " + future1.get(1, TimeUnit.SECONDS));
        } catch (TimeoutException e) {
            System.out.println("Task 1 timed out");
        }

        System.out.println("Result of task2: " + future2.get());

        executor.shutdown();
    }
}
解答

Task 1 timed out
Result of task2: Task 2
タスク1はタイムアウトし、タスク2の結果が出力されます。

問 37

import java.util.concurrent.*;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(4);

        CountDownLatch latch = new CountDownLatch(4);
        IntStream.range(0, 4).forEach(i -> executor.submit(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("Task " + i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }
        }));

        latch.await();
        System.out.println("All tasks finished");

        executor.shutdown();
    }
}
解答

Task 0
Task 1
Task 2
Task 3
All tasks finished
4つのタスクが完了した後、「All tasks finished」が出力されます。

問 38

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        ScheduledFuture<?> future = scheduler.scheduleWithFixedDelay(() -> {
            System.out.println("Periodic task");
        }, 0, 1, TimeUnit.SECONDS);

        Thread.sleep(5000);
        future.cancel(false);
        scheduler.shutdown();
    }
}
解答

Periodic task
Periodic task
Periodic task
Periodic task
1秒間隔で定期的にタスクが実行され、5秒後にキャンセルされます。

問 39

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        CyclicBarrier barrier = new CyclicBarrier(3, () -> System.out.println("Barrier action"));

        Runnable task = () -> {
            try {
                System.out.println(Thread.currentThread().getName() + " reached barrier");
                barrier.await();
                System.out.println(Thread.currentThread().getName() + " passed barrier");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        };

        executor.submit(task);
        executor.submit(task);
        executor.submit(task);

        executor.shutdown();
    }
}
解答

Thread-0 reached barrier
Thread-1 reached barrier
Thread-2 reached barrier
Barrier action
Thread-0 passed barrier
Thread-1 passed barrier
Thread-2 passed barrier
3つのタスクがバリアに到達し、全てがバリアを通過するまで待機します。

問 40

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        AtomicBoolean flag = new AtomicBoolean(true);

        Runnable task = () -> {
            if (flag.getAndSet(false)) {
                System.out.println(Thread.currentThread().getName() + " set the flag to false");
            } else {
                System.out.println(Thread.currentThread().getName() + " flag is already false");
            }
        };

        executor.submit(task);
        executor.submit(task);

        executor.shutdown();
    }
}
解答

Thread-0 set the flag to false
Thread-1 flag is already false
`AtomicBoolean`を使用して、フラグの状態が正しく管理されます。
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?