-
Notifications
You must be signed in to change notification settings - Fork 103
Lesson 60 (thread) #105
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: for-pr
Are you sure you want to change the base?
Lesson 60 (thread) #105
Changes from all commits
bc42716
cd11dcd
3ccbed5
849a755
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,10 +1,40 @@ | ||
| package com.walking.lesson60_thread.task1; | ||
|
|
||
| import java.time.Duration; | ||
| import java.time.LocalDateTime; | ||
| import java.time.format.DateTimeFormatter; | ||
| import java.time.format.FormatStyle; | ||
| import java.time.temporal.ChronoUnit; | ||
|
|
||
| /** | ||
| * Напишите программу, которая пишет в консоль текущее время каждый две секунды, | ||
| * пока программа запущена. | ||
| */ | ||
| public class Main { | ||
| public static void main(String[] args) { | ||
| public static void main(String[] args) throws InterruptedException { | ||
| Duration twoSeconds = Duration.of(2, ChronoUnit.SECONDS); | ||
|
|
||
| DateTimeFormatter mediumTimeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM); | ||
|
|
||
| Thread timePrinter = new Thread(printTimeCyclical(twoSeconds, mediumTimeFormatter), "timePrinter"); | ||
|
|
||
| timePrinter.start(); | ||
| } | ||
|
|
||
| public static Runnable printTimeCyclical(Duration duration, DateTimeFormatter formatter) { | ||
| return () -> { | ||
| while (!Thread.currentThread() | ||
| .isInterrupted()) { | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. в общем-то, логика понятна, но практически избыточна. Как правило, проверка на прерывание используется тогда, когда действительно есть шанс, что поток будет прерван |
||
| System.out.println(LocalDateTime.now() | ||
| .format(formatter)); | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. подобные переносы выглядят не очень. Лучше уж в одну строку. Или выноси в переменную, если хочется перенести |
||
|
|
||
| try { | ||
| Thread.sleep(duration); | ||
| } catch (InterruptedException e) { | ||
| Thread.currentThread() | ||
| .interrupt(); | ||
| } | ||
| } | ||
| }; | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. как по мне - переусложнил, но в точки зрения попрактиковаться с новым API - норм |
||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,14 @@ | ||
| package com.walking.lesson60_thread.task2; | ||
|
|
||
| import com.walking.lesson60_thread.task2.model.ExtremeMultiThreadTableFiller; | ||
| import com.walking.lesson60_thread.task2.model.MultiThreadTableFiller; | ||
| import com.walking.lesson60_thread.task2.model.SingleThreadTableFiller; | ||
| import com.walking.lesson60_thread.task2.model.TableFiller; | ||
|
|
||
| import java.time.Duration; | ||
| import java.time.LocalTime; | ||
| import java.util.Random; | ||
|
|
||
| /** | ||
| * Опишите интерфейс, декларирующий метод, заполняющий двумерный массив заданных размеров | ||
| * случайными числами от 1 до 10. | ||
|
|
@@ -11,6 +20,30 @@ | |
| * динамически-определяемым в зависимости от размера массива*. | ||
| */ | ||
| public class Main { | ||
| public static void main(String[] args) { | ||
| public static void main(String[] args) throws InterruptedException { | ||
| LocalTime startTime = LocalTime.now(); | ||
|
|
||
| Random random = new Random(); | ||
| int[][] numbers = new int[10][10_000_000]; | ||
| TableFiller tableFiller = new MultiThreadTableFiller(); | ||
|
|
||
| tableFiller.fillTable(numbers, () -> random.nextInt(1, 11)); | ||
|
|
||
| // print2DArray(numbers); | ||
|
|
||
| LocalTime endTime = LocalTime.now(); | ||
|
|
||
| System.out.printf("Overall time = %s\n".formatted(Duration.between(startTime, endTime) | ||
| .toMillis())); | ||
| } | ||
|
|
||
| public static <T> void print2DArray(int[][] array) { | ||
| for (int[] row : array) { | ||
| for (int column : row) { | ||
| System.out.printf("[%s]".formatted(column)); | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. если printf() - formatted() лишний |
||
| } | ||
|
|
||
| System.out.println(); | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| package com.walking.lesson60_thread.task2.model; | ||
|
|
||
| import java.util.function.IntSupplier; | ||
|
|
||
| public class ExtremeMultiThreadTableFiller implements TableFiller { | ||
| private static final int MAX_ELEMENTS_IN_THREAD = 500_000_000; | ||
|
|
||
| @Override | ||
| public void fillTable(int[][] table, IntSupplier value) throws InterruptedException { | ||
| Thread tableFiller = new Thread(tableFillingProcess(table, value), "tableFiller"); | ||
|
|
||
| tableFiller.start(); | ||
|
|
||
| tableFiller.join(); | ||
| } | ||
|
|
||
| private Runnable tableFillingProcess(int[][] table, IntSupplier value) throws InterruptedException { | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. методы именуются с глагола |
||
| return () -> { | ||
| /* List<Thread> threadList = new ArrayList<>(table.length);*/ | ||
|
|
||
| for (int[] row : table) { | ||
| int partCount = Math.max(1, row.length / MAX_ELEMENTS_IN_THREAD); | ||
|
|
||
| Thread rowFiller = new Thread(() -> { | ||
| try { | ||
| fillRow(row, partCount, value); | ||
| } catch (InterruptedException e) { | ||
| throw new RuntimeException(e); | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Зачем? В каком случае может вывалиться интерраптед ниже по стеку?
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. как будто join закомментил, а здесь не подчистил |
||
| } | ||
| }, "rowFiller"); | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. имена тредов обычно не задаются вручную - в этом мало смысла, пока нет тред пулов. С ними познакомишься позже (или уже познакомился) |
||
|
|
||
| /* threadList.add(rowFiller);*/ | ||
|
|
||
| rowFiller.start(); | ||
| } | ||
|
|
||
| /*for (Thread thread : threadList) { | ||
| try { | ||
| thread.join(); | ||
| } catch (InterruptedException e) { | ||
| throw new RuntimeException(e); | ||
| } | ||
| }*/ | ||
| }; | ||
| } | ||
|
|
||
| private void fillRow(int[] row, int partCount, IntSupplier value) throws InterruptedException { | ||
| /*List<Thread> threadList = new ArrayList<>(partCount);*/ | ||
|
|
||
| int offset = row.length / partCount; | ||
| int startIndex = 0; | ||
| int endIndex = offset; | ||
|
|
||
| for (int i = 0; i < partCount; i++) { | ||
| fillRowPart(row, startIndex, endIndex, value/*, threadList*/); | ||
|
|
||
| startIndex += offset; | ||
| endIndex += offset; | ||
| } | ||
|
|
||
| /*for (Thread thread : threadList) { | ||
| thread.join(); | ||
| }*/ | ||
| } | ||
|
|
||
| private void fillRowPart(int[] row, int startInclusive, int endExclusive, | ||
| IntSupplier value/*, List<Thread> threadList*/) throws InterruptedException { | ||
| Thread partRowFiller = new Thread(partRowFillingProcess(row, startInclusive, endExclusive, value), | ||
| "partRowFiller"); | ||
|
|
||
| /*threadList.add(partRowFiller);*/ | ||
|
|
||
| partRowFiller.start(); | ||
| } | ||
|
|
||
| private Runnable partRowFillingProcess(int[] row, int startInclusive, int endExclusive, IntSupplier value) { | ||
| return () -> { | ||
| for (int i = startInclusive; i < endExclusive; i++) { | ||
| row[i] = value.getAsInt(); | ||
| } | ||
| }; | ||
| } | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. как будто можно было описать лаконичнее/декомпозировать иначе. И, опять же, переусложняешь |
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| package com.walking.lesson60_thread.task2.model; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.Arrays; | ||
| import java.util.List; | ||
| import java.util.function.IntSupplier; | ||
|
|
||
| public class MultiThreadTableFiller implements TableFiller { | ||
| @Override | ||
| public void fillTable(int[][] table, IntSupplier value) throws InterruptedException { | ||
| Thread tableFiller = new Thread(tableFillingProcess(table, value), "tableFiller"); | ||
|
|
||
| tableFiller.start(); | ||
|
|
||
| tableFiller.join(); | ||
| } | ||
|
|
||
| private Runnable tableFillingProcess(int[][] table, IntSupplier value) { | ||
| return () -> { | ||
| List<Thread> threadList = new ArrayList<>(table.length); | ||
|
|
||
| for (int[] row : table) { | ||
| Thread rowFiller = new Thread(() -> { | ||
| Arrays.setAll(row, x -> value.getAsInt()); | ||
|
|
||
| }, "rowFiller"); | ||
|
|
||
| threadList.add(rowFiller); | ||
|
|
||
| rowFiller.start(); | ||
| } | ||
|
|
||
| for (Thread thread : threadList) { | ||
| try { | ||
| thread.join(); | ||
| } catch (InterruptedException e) { | ||
| throw new RuntimeException(e); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. В виде стрима получилось бы красивее:) |
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| package com.walking.lesson60_thread.task2.model; | ||
|
|
||
| import java.util.Arrays; | ||
| import java.util.function.IntSupplier; | ||
|
|
||
| public class SingleThreadTableFiller implements TableFiller { | ||
| @Override | ||
| public void fillTable(int[][] table, IntSupplier value) throws InterruptedException { | ||
| Thread tableFiller = new Thread(tableFillingProcess(table, value), "tableFiller"); | ||
|
|
||
| tableFiller.start(); | ||
|
|
||
| tableFiller.join(); | ||
| } | ||
|
|
||
| private Runnable tableFillingProcess(int[][] table, IntSupplier value) { | ||
| return () -> { | ||
| for (int[] row : table) { | ||
| Arrays.setAll(row, x -> value.getAsInt()); | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Даже не знал о таком методе:) |
||
| } | ||
| }; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| package com.walking.lesson60_thread.task2.model; | ||
|
|
||
| import java.util.function.IntSupplier; | ||
|
|
||
| public interface TableFiller { | ||
| void fillTable(int[][] table, IntSupplier value) throws InterruptedException; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| package com.walking.lesson60_thread.task3.model; | ||
|
|
||
| import java.util.concurrent.Callable; | ||
| import java.util.function.Function; | ||
|
|
||
| public class FunctionExecutor<T, R> implements Callable<R> { | ||
| T value; | ||
| Function<T, R> function; | ||
| R result; | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. что с идентификаторами доступа? |
||
|
|
||
| public FunctionExecutor(T value, Function<T, R> function) { | ||
| this.value = value; | ||
| this.function = function; | ||
| } | ||
|
|
||
| @Override | ||
| public R call() throws InterruptedException { | ||
| Thread thread = new Thread(() -> result = function.apply(value), "thread"); | ||
|
|
||
| thread.start(); | ||
|
|
||
| thread.join(); | ||
|
|
||
| return result; | ||
| } | ||
| } | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Намудрил. Зачем Callable в этом решении? Здесь он как будто из-за рекомендации в условии. Но именно в этой имплементации он оказался не нужен:) Также, почему Function? Вполне возможна ситуация, когда входного параметра нет. Или их несколько. Как будто неудачный подбор функционального интерфейса |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,9 +1,25 @@ | ||
| package com.walking.lesson60_thread.task4; | ||
|
|
||
| import com.walking.lesson60_thread.task4.model.FunctionExecutor; | ||
|
|
||
| import java.util.Random; | ||
|
|
||
| /** | ||
| * Решите Задачу 3, не используя Thread.join(). | ||
| */ | ||
| public class Main { | ||
| public static void main(String[] args) { | ||
| public static void main(String[] args) throws InterruptedException { | ||
| FunctionExecutor<String, Integer> lengthCalculator = new FunctionExecutor<>("Test_string", String::length); | ||
|
|
||
| System.out.println(lengthCalculator.call()); | ||
|
|
||
| FunctionExecutor<String, String> toUpperCase = new FunctionExecutor<>("Test_string", String::toUpperCase); | ||
|
|
||
| System.out.println(toUpperCase.call()); | ||
|
|
||
| FunctionExecutor<Integer, String> oddOrEvenPrinter = new FunctionExecutor<>(new Random().nextInt(10), | ||
| i -> i % 2 == 0 ? "%s is even".formatted(i) : "%s is odd".formatted(i)); | ||
|
|
||
| System.out.println(oddOrEvenPrinter.call()); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| package com.walking.lesson60_thread.task4.model; | ||
|
|
||
| import java.util.concurrent.Callable; | ||
| import java.util.function.Function; | ||
|
|
||
| public class FunctionExecutor<T, R> implements Callable<R> { | ||
| T value; | ||
| Function<T, R> function; | ||
| R result; | ||
|
|
||
| public FunctionExecutor(T value, Function<T, R> function) { | ||
| this.value = value; | ||
| this.function = function; | ||
| } | ||
|
|
||
| @Override | ||
| public R call() throws InterruptedException { | ||
| Thread thread = new Thread(() -> result = function.apply(value), "thread"); | ||
|
|
||
| thread.start(); | ||
|
|
||
| while (true) { | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. можно упростить, засунув условие if в условие цикла |
||
| if (!thread.isAlive()) { | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| return result; | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
избыточная переменная