Skip to content

Commit 1bda03e

Browse files
committed
29.12.2016
1 parent 4c18de4 commit 1bda03e

File tree

8 files changed

+306
-0
lines changed

8 files changed

+306
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.javarush.test.level30.lesson02.task01;
2+
3+
import java.math.BigInteger;
4+
5+
/* Осваиваем методы класса Integer
6+
Используя метод Integer.parseInt(String, int) реализуйте логику метода convertToDecimalSystem,
7+
который должен переводить переданную строку в десятичное число и возвращать его в виде строки.
8+
*/
9+
public class Solution {
10+
11+
public static void main(String[] args) {
12+
System.out.println(convertToDecimalSystem("0x16")); //22
13+
System.out.println(convertToDecimalSystem("012")); //10
14+
System.out.println(convertToDecimalSystem("0b10")); //2
15+
System.out.println(convertToDecimalSystem("62")); //62
16+
}
17+
18+
public static String convertToDecimalSystem(String s) {
19+
if (s.contains("b")) {
20+
return String.valueOf(Integer.parseInt(s.substring(s.indexOf("b")+1), 2));
21+
}
22+
23+
return String.valueOf(Integer.decode(s));
24+
}
25+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.javarush.test.level30.lesson04.home01;
2+
3+
import java.util.concurrent.TransferQueue;
4+
5+
/**
6+
* Created by ukr-sustavov on 28.12.2016.
7+
*/
8+
public class Consumer implements Runnable {
9+
private TransferQueue<ShareItem> shareItem;
10+
11+
public Consumer(TransferQueue<ShareItem> shareItem) {
12+
this.shareItem = shareItem;
13+
}
14+
15+
16+
@Override
17+
public void run() {
18+
try {
19+
Thread.sleep(500);
20+
} catch (InterruptedException e) {
21+
e.printStackTrace();
22+
}
23+
while (true) {
24+
try {
25+
ShareItem item = shareItem.take();
26+
System.out.println("Processing " + item.toString());
27+
} catch (InterruptedException e) {
28+
// e.printStackTrace();
29+
}
30+
}
31+
32+
}
33+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.javarush.test.level30.lesson04.home01;
2+
3+
import java.util.concurrent.TransferQueue;
4+
5+
/**
6+
* Created by ukr-sustavov on 28.12.2016.
7+
*/
8+
public class Producer implements Runnable {
9+
private TransferQueue<ShareItem> shareItem;
10+
11+
public Producer(TransferQueue<ShareItem> shareItem) {
12+
this.shareItem = shareItem;
13+
}
14+
15+
@Override
16+
public void run() {
17+
for (int i = 1; i < 10; i++) {
18+
final int j = i;
19+
System.out.format("Элемент 'ShareItem-%s' добавлен \n", j);
20+
shareItem.offer(new ShareItem("ShareItem-" + j, j));
21+
try {
22+
Thread.sleep(100);
23+
} catch (InterruptedException e) {
24+
// e.printStackTrace();
25+
}
26+
if (shareItem.getWaitingConsumerCount() > 0) {
27+
System.out.println("Consumer в ожидании!");
28+
}
29+
30+
}
31+
}
32+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.javarush.test.level30.lesson04.home01;
2+
3+
//this class shows how to call other constructors using 'this'
4+
public class ShareItem {
5+
public String description;
6+
public int itemId;
7+
8+
public ShareItem() {
9+
this("Test Item", 0);
10+
}
11+
12+
public ShareItem(String description) {
13+
this(description, 0);
14+
}
15+
16+
public ShareItem(int itemId) {
17+
this("Test Item", itemId);
18+
}
19+
20+
public ShareItem(String description, int itemId) {
21+
this.description = description;
22+
this.itemId = itemId;
23+
}
24+
25+
public String getDescription() {
26+
return description;
27+
}
28+
29+
public int getItemId() {
30+
return itemId;
31+
}
32+
33+
@Override
34+
public String toString() {
35+
return "ShareItem{" +
36+
"description='" + description + '\'' +
37+
", itemId=" + itemId +
38+
'}';
39+
}
40+
41+
@Override
42+
public boolean equals(Object o) {
43+
if (this == o) return true;
44+
if (o == null || getClass() != o.getClass()) return false;
45+
46+
ShareItem shareItem = (ShareItem) o;
47+
48+
if (itemId != shareItem.itemId) return false;
49+
return !(description != null ? !description.equals(shareItem.description) : shareItem.description != null);
50+
51+
}
52+
53+
@Override
54+
public int hashCode() {
55+
int result = description != null ? description.hashCode() : 0;
56+
result = 31 * result + itemId;
57+
return result;
58+
}
59+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.javarush.test.level30.lesson04.home01;
2+
3+
import java.util.concurrent.LinkedTransferQueue;
4+
import java.util.concurrent.TransferQueue;
5+
6+
/* Экономим время
7+
1. Создайте Producer и Consumer (См. комментарий к методу main)
8+
2. Создайте методы toString, equals и hashCode в классе ShareItem. Для этого в теле класса ShareItem выполни:
9+
2.1. Alt+Enter -> toString() -> Enter
10+
2.2. Alt+Enter -> equals() and hashCode() -> click all 'Next'-s
11+
3. В Producer и Consumer реализуйте метод run так, чтобы вызов метода interrupt прерывал работу consumer и producer трэдов
12+
13+
4. Реализация метода run для Producer:
14+
4.1. Используя метод offer добавить в очередь 9 ShareItem-ов с такими параметрами: ("ShareItem-N", N), где N - номер элемента от 1 до 9
15+
4.2. Перед каждым добавлением вывести фразу "Элемент 'ShareItem-N' добавлен". Используйте System.out.format
16+
4.3. Усыпить трэд на 0.1 секунды
17+
4.4. Если у очереди есть Consumer, не занятый работой, то вывести фразу "Consumer в ожидании!".
18+
Просмотрите методы интерфейса TransferQueue, там есть нужный метод.
19+
20+
5. Реализация метода run для Consumer:
21+
5.1. Усыпить трэд на 0.5 секунды
22+
5.2. В бесконечном цикле заберите элемент из очереди методом take и выведите в консоль "Processing item.toString()".
23+
24+
6. Сверьте вывод с файлом output.txt
25+
7. Стек-трейс не выводите в консоль
26+
*/
27+
public class Solution {
28+
/*
29+
1. Создайте класс Producer. Для этого на красном имени класса нажмите Alt+Enter -> Create Class ...
30+
2. Станьте на имени аргумента в конструкторе (queue) и нажмите Alt+Enter -> Create Field for Parameter 'queue' -> Enter -> Enter
31+
3. Станьте на подчеркнутой строке - описании класса. Далее Alt+Enter -> Implement Methods -> Enter
32+
4. Проделайте п.1-3 для класса Consumer
33+
*/
34+
35+
public static void main(String[] args) throws InterruptedException {
36+
TransferQueue<ShareItem> queue = new LinkedTransferQueue<>();
37+
38+
Thread producer = new Thread(new Producer(queue));
39+
Thread consumer = new Thread(new Consumer(queue));
40+
producer.start();
41+
consumer.start();
42+
43+
Thread.sleep(1500);
44+
45+
producer.interrupt();
46+
consumer.interrupt();
47+
}
48+
49+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.javarush.test.level30.lesson06.home01;
2+
3+
import java.util.concurrent.RecursiveTask;
4+
5+
/**
6+
* Created by ukr-sustavov on 28.12.2016.
7+
*/
8+
public class BinaryRepresentationTask extends RecursiveTask<String> {
9+
private int i;
10+
11+
public BinaryRepresentationTask(int i) {
12+
this.i = i;
13+
}
14+
15+
@Override
16+
protected String compute() {
17+
18+
return null;
19+
}
20+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.javarush.test.level30.lesson06.home01;
2+
3+
import java.util.concurrent.ForkJoinPool;
4+
5+
/* Fork/Join
6+
1. Создайте класс BinaryRepresentationTask. Для этого на красном имени класса нажмите Alt+Enter -> Create Class ...
7+
(класс должен наследоваться от RecursiveTask)
8+
2. Реализуйте логику метода compute, должна переводить число в двоичное представление.
9+
3. Используйте методы fork и join.
10+
4. Пример функциональной реализации - метод binaryRepresentationMethod.
11+
*/
12+
public class Solution {
13+
private String binaryRepresentationMethod(int x) {
14+
int a = x % 2;
15+
int b = x / 2;
16+
String result = String.valueOf(a);
17+
if (b > 0) {
18+
return binaryRepresentationMethod(b) + result;
19+
}
20+
return result;
21+
}
22+
23+
public static void main(String[] args) {
24+
Solution solution = new Solution();
25+
String result1 = solution.binaryRepresentationMethod(6);
26+
System.out.println(result1);
27+
28+
System.out.println();
29+
ForkJoinPool forkJoinPool = new ForkJoinPool();
30+
String result2 = forkJoinPool.invoke(new BinaryRepresentationTask(6));
31+
System.out.println(result2);
32+
}
33+
34+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.javarush.test.level30.lesson06.task01;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/* Такие хитрые исключения!
7+
Исправьте реализацию метода checkAFlag, чтобы во всех случаях он не приводил к бросанию исключений.
8+
Сохраните логику вывода данных.
9+
Метод main не участвует в тестировании.
10+
*/
11+
public class Solution {
12+
public static void main(String[] args) {
13+
checkAFlag(new D());
14+
// checkAFlag(new D().cs.get(0));
15+
}
16+
17+
public static void checkAFlag(D d) {
18+
if ((d != null && d.cs != null && !d.cs.isEmpty()) &&
19+
(d.cs != null && d.cs.get(0) != null && d.cs.get(0).bs != null && !d.cs.get(0).bs.isEmpty()) &&
20+
(d.cs.get(0).bs != null && d.cs.get(0).bs.get(0) != null && d.cs.get(0).bs.get(0).as != null && !d.cs.get(0).bs.get(0).as.isEmpty()) &&
21+
(d.cs.get(0).bs.get(0).as != null && d.cs.get(0).bs.get(0).as.get(0) != null && d.cs.get(0).bs.get(0).as.get(0).flag))
22+
{
23+
System.out.println("A's flag is true");
24+
} else
25+
{ //all other cases
26+
System.out.println("Oops!");
27+
}
28+
}
29+
30+
static class A {
31+
boolean flag = true;
32+
}
33+
34+
static class B {
35+
List<A> as = new ArrayList<>();
36+
{
37+
as.add(new A());
38+
}
39+
}
40+
41+
static class C {
42+
List<B> bs = new ArrayList<>();
43+
{
44+
bs.add(new B());
45+
}
46+
}
47+
48+
static class D {
49+
List<C> cs = new ArrayList<>();
50+
{
51+
cs.add(new C());
52+
}
53+
}
54+
}

0 commit comments

Comments
 (0)