Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion src/com/walking/lesson60_thread/task1/Main.java
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");
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

избыточная переменная


timePrinter.start();
}

public static Runnable printTimeCyclical(Duration duration, DateTimeFormatter formatter) {
return () -> {
while (!Thread.currentThread()
.isInterrupted()) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

в общем-то, логика понятна, но практически избыточна. Как правило, проверка на прерывание используется тогда, когда действительно есть шанс, что поток будет прерван

System.out.println(LocalDateTime.now()
.format(formatter));
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

подобные переносы выглядят не очень. Лучше уж в одну строку. Или выноси в переменную, если хочется перенести


try {
Thread.sleep(duration);
} catch (InterruptedException e) {
Thread.currentThread()
.interrupt();
}
}
};
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

как по мне - переусложнил, но в точки зрения попрактиковаться с новым API - норм

}
}
35 changes: 34 additions & 1 deletion src/com/walking/lesson60_thread/task2/Main.java
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.
Expand All @@ -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));
Copy link
Owner

Choose a reason for hiding this comment

The 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 {
Copy link
Owner

Choose a reason for hiding this comment

The 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);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем? В каком случае может вывалиться интерраптед ниже по стеку?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

как будто join закомментил, а здесь не подчистил

}
}, "rowFiller");
Copy link
Owner

Choose a reason for hiding this comment

The 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();
}
};
}
Copy link
Owner

Choose a reason for hiding this comment

The 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);
}
}
};
}
Copy link
Owner

Choose a reason for hiding this comment

The 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());
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Даже не знал о таком методе:)

}
};
}
}
7 changes: 7 additions & 0 deletions src/com/walking/lesson60_thread/task2/model/TableFiller.java
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;
}
18 changes: 17 additions & 1 deletion src/com/walking/lesson60_thread/task3/Main.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package com.walking.lesson60_thread.task3;

import com.walking.lesson60_thread.task3.model.FunctionExecutor;

import java.util.Random;

/**
* Уже на текущем этапе мы можем распараллелить какие-то действия с помощью многопоточности.
* Но иногда требуется выполнить определенную операцию в другом потоке и получить ее результат.
Expand All @@ -10,6 +14,18 @@
* Его метод имеет возвращаемое значение.
*/
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());
}
}
26 changes: 26 additions & 0 deletions src/com/walking/lesson60_thread/task3/model/FunctionExecutor.java
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;
Copy link
Owner

Choose a reason for hiding this comment

The 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;
}
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Намудрил. Зачем Callable в этом решении? Здесь он как будто из-за рекомендации в условии. Но именно в этой имплементации он оказался не нужен:)

Также, почему Function? Вполне возможна ситуация, когда входного параметра нет. Или их несколько. Как будто неудачный подбор функционального интерфейса

18 changes: 17 additions & 1 deletion src/com/walking/lesson60_thread/task4/Main.java
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());
}
}
30 changes: 30 additions & 0 deletions src/com/walking/lesson60_thread/task4/model/FunctionExecutor.java
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) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

можно упростить, засунув условие if в условие цикла

if (!thread.isAlive()) {
break;
}
}

return result;
}
}