Skip to content

Лабароторная 1 иванков#10

Open
deadlovelll wants to merge 10 commits intomasterfrom
master
Open

Лабароторная 1 иванков#10
deadlovelll wants to merge 10 commits intomasterfrom
master

Conversation

@deadlovelll
Copy link

No description provided.

// Running 10 iterations
for (int i = 0; i < 10; i++) {
// Generating random nums
int programmersCount = rand.nextInt(MAX);

Choose a reason for hiding this comment

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

Предлагаю сделать конфиг не рандомом и не хардкодом, чтобы можно было легко менять без рекомпила

Copy link
Author

Choose a reason for hiding this comment

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

Исправил, теперь значения лежат в конфиге

@Override
public void run() {
try {
while (true) {

Choose a reason for hiding this comment

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

Кажется можно переписать так, чтобы не торчало while true

Copy link
Author

Choose a reason for hiding this comment

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

Исправил, теперь цикл выглядит так:

    @Override
    public void run() {
        try {
            // Trying to eat while food is here
            while (!forks.isEmpty() && takeOnePortionIfAvailable()) {
                boolean ate = false;
                // Trying while the programmer eat
                while (!ate) {
                    // If grabbed forks - eat
                    if (grabForks()) {
                        try {
                            EatDinnder();
                            ate = true;
                        } finally {
                            ReleaseForks();
                        }
                    } else {
                        Thread.sleep(50);
                    }
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    ```

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

public class Programmer extends Thread {

Choose a reason for hiding this comment

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

Как будто делать все это на голых тредах плохая идея, столько всяких штук на лекции и практики рассмотрели...

Choose a reason for hiding this comment

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

Как у вас обеспечивается равномерность поедания? В текущей реализации кажется, что чем шире будет диапазон рандома времени поедания, тем больше будет разброс накормленности

Copy link
Author

@deadlovelll deadlovelll Oct 1, 2025

Choose a reason for hiding this comment

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

Но по крайней мере это получилось. Да с равномерностью были в некоторых случаях проблемы,
проанализировав пришел к двум выводам:

  1. Нужно использовать лок вместо синхронайза
  2. Не забирать из хэшмапа вилки
  3. Убрать из EatDinnder sleep  с рандомным шумом

После этого результаты стали такие:

П - Программисты, ПЕ - порций еды

50П, 150ПЕ:

--------------------------------------------------------------------
Programmers: 50
Food: 150
Dinner is over!
Food amount is 0
Portions eaten: 1, Count: 3
Portions eaten: 2, Count: 12
Portions eaten: 3, Count: 23
Portions eaten: 4, Count: 7
Portions eaten: 5, Count: 4
Portions eaten: 6, Count: 1
-----------------------------

50П, 100ПЕ:

--------------------------------------------------------------------
Programmers: 50
Food: 100
Dinner is over!
Food amount is 0
Portions eaten: 1, Count: 9
Portions eaten: 2, Count: 32
Portions eaten: 3, Count: 9
--------------------------------------------------------------------

50П, 50ПЕ:

--------------------------------------------------------------------
Programmers: 50
Food: 50
Dinner is over!
Food amount is 0
Portions eaten: 1, Count: 50
--------------------------------------------------------------------

Copy link
Author

Choose a reason for hiding this comment

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

50П 750ПЕ

--------------------------------------------------------------------
Programmers: 50
Food: 750
Dinner is over!
Food amount is 0
Portions eaten: 8, Count: 1
Portions eaten: 11, Count: 1
Portions eaten: 12, Count: 7
Portions eaten: 13, Count: 9
Portions eaten: 14, Count: 10
Portions eaten: 15, Count: 7
Portions eaten: 16, Count: 6
Portions eaten: 17, Count: 2
Portions eaten: 18, Count: 2
Portions eaten: 19, Count: 1
Portions eaten: 21, Count: 2
Portions eaten: 28, Count: 1
Portions eaten: 30, Count: 1

Copy link
Author

Choose a reason for hiding this comment

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

Получается что при небольших значениях, все едят одинаково,
При огромных значениях большинство есть одинаково, аномальные выбросы есть, но они единичны

Все остаются сытыми

while (!ate) {
// If successfully grabbed forks
// - eat
if (grabForks(this.forks)) {

Choose a reason for hiding this comment

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

Какой то страшный каскад всего подряд, еще и вложенные циклы. Постарайтесь пж отрефакторить, чтобы выглядело поаккуратнее

Copy link
Author

Choose a reason for hiding this comment

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

Сделал лучше

@deadlovelll
Copy link
Author

Внес все правки о которых вы говорили, так же добавил семафор. Получился намного меньше разброс

> Task :run
--------------------------------------------------------------------
Programmers: 50
Food: 1000
Dinner is over!
Food amount is 0
Portions eaten: 2, Count: 1
Portions eaten: 18, Count: 1
Portions eaten: 20, Count: 1
Portions eaten: 4, Count: 2
Portions eaten: 22, Count: 28
Portions eaten: 6, Count: 1
Portions eaten: 23, Count: 13
Portions eaten: 8, Count: 1
Portions eaten: 9, Count: 1
Portions eaten: 14, Count: 1
--------------------------------------------------------------------
--------------------------------------------------------------------
Programmers: 50
Food: 1000
Dinner is over!
Food amount is 0
Portions eaten: 2, Count: 2
Portions eaten: 3, Count: 4
Portions eaten: 22, Count: 28
Portions eaten: 23, Count: 16
--------------------------------------------------------------------
--------------------------------------------------------------------
Programmers: 50
Food: 1000
Dinner is over!
Food amount is 0
Portions eaten: 20, Count: 36
Portions eaten: 21, Count: 13
Portions eaten: 7, Count: 1
--------------------------------------------------------------------
--------------------------------------------------------------------
Programmers: 50
Food: 1000
Dinner is over!
Food amount is 0
Portions eaten: 1, Count: 1
Portions eaten: 20, Count: 24
Portions eaten: 21, Count: 24
Portions eaten: 15, Count: 1
--------------------------------------------------------------------
--------------------------------------------------------------------
Programmers: 50
Food: 1000
Dinner is over!
Food amount is 0
Portions eaten: 20, Count: 50
--------------------------------------------------------------------
--------------------------------------------------------------------
Programmers: 50
Food: 1000
Dinner is over!
Food amount is 0
Portions eaten: 20, Count: 50
--------------------------------------------------------------------
--------------------------------------------------------------------
Programmers: 50
Food: 1000
Dinner is over!
Food amount is 0
Portions eaten: 19, Count: 1
Portions eaten: 20, Count: 33
Portions eaten: 21, Count: 15
Portions eaten: 6, Count: 1
--------------------------------------------------------------------
--------------------------------------------------------------------
Programmers: 50
Food: 1000
Dinner is over!
Food amount is 0
Portions eaten: 2, Count: 1
Portions eaten: 20, Count: 17
Portions eaten: 21, Count: 31
Portions eaten: 7, Count: 1
--------------------------------------------------------------------
--------------------------------------------------------------------
Programmers: 50
Food: 1000
Dinner is over!
Food amount is 0
Portions eaten: 20, Count: 38
Portions eaten: 21, Count: 11
Portions eaten: 9, Count: 1
--------------------------------------------------------------------
--------------------------------------------------------------------
Programmers: 50
Food: 1000
Dinner is over!
Food amount is 0
Portions eaten: 20, Count: 50
--------------------------------------------------------------------

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants