-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSolution.java
More file actions
80 lines (56 loc) · 3.16 KB
/
Copy pathSolution.java
File metadata and controls
80 lines (56 loc) · 3.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//For I testify unto every man that heareth the words of the prophecy of this book, If any man shall add unto these things,
//God shall add unto him the plagues that are written in this book: (Revelation 22:18)
package com.javarush.task.task29.task2903;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ThreadLocalRandom;
/*
И еще раз рефакторинг
*/
public class Solution {
public static final ThreadLocalRandom RANDOM = ThreadLocalRandom.current();
public static void main(String[] args) {
ConcurrentMap<Integer, String> concurrentMap = new ConcurrentHashMap<>();
for (int i = 0; i < 100; i++) {
new Thread(getRunnable(i, concurrentMap)).start();
}
sleepASecond();
}
private static void sleepASecond() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static Runnable getRunnable(final int i, final ConcurrentMap<Integer, String> concurrentMap) {
return new Runnable() {
@Override
public void run() {
final String name = "Thread #" + i;
int randomInt = RANDOM.nextInt(20);
String text = name + " вставил запись для " + randomInt;
//previousEntry is null if it is new entry
/* instead of null - call concurrentMap.someMethodName(randomInt, text)*/
String previousEntry = concurrentMap.putIfAbsent(randomInt, text);
if (previousEntry != null) {
System.out.println(name + " хочет обновить " + randomInt + ", однако уже " + previousEntry);
} else {
System.out.println(text);
}
}
};
}
}
/*
И еще раз рефакторинг
1. Исправить код в соответствии с Naming and Code Convention (Shift+F6 для рефакторинга)
2. Просмотри методы класса ConcurrentMap.
3. В строке "String previousEntry = null;" у concurrentMap вызови метод, который вставит пару (randomInt, text) только для ключа, которого нет в concurrentMap.
(Вызванный метод должен возвращать предыдущее значение либо null для новой пары.)
Требования:
1. Переименуй константу random в соответствии с Naming and Code Convention.
2. Объект, возвращаемый методом getRunnable, должен быть экземпляром анонимного класса.
3. Метод run внутри метода getRunnable должен вызывать у concurrentMap метод, вставляющий пару (randomInt, text), если в concurrentMap еще нет пары со значением ключа randomInt.
4. Метод run класса, возвращаемого методом getRunnable, должен выводить текст на экран.
*/