Смотритель: hubert
  • ,

Прерывания работы нити (interrupte thread).

Набросал два класса, наследующихся от Runnable. В них простая начинка ( Thread.sleep и sout). Я изучал вопрос прерывания работы нитей при помощи interrupted и isInterrupted. Почему-то прерывания не происходит, а выполнение программы зациклавается и вылетает ошибка:
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.javarush.test.myExample.example.thread.Producer.run(Producer.java:15)
	at java.lang.Thread.run(Thread.java:745)
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.javarush.test.myExample.example.thread.Consumer.run(Consumer.java:15)
	at java.lang.Thread.run(Thread.java:745)

После вылета ошибки работа нитей продолжается бесконечно. Но если убрать из классов, унаследовавшихся от Runnable, вызов Thread.sleep, то программа отрабатывает нормально. В чем загвоздка, почему вылетает ошибка и почему не завершается работа программы???
Вот main:
public class Solution
    public static void main(String[] args) throws InterruptedException
        Thread thread1 = new Thread(new Producer());
        Thread thread2 = new Thread(new Consumer());




Первый класс:
public class Producer implements Runnable
    public void run()
        while (!Thread.interrupted())
            catch (InterruptedException e)

Второй класс:
public class Consumer implements Runnable
    public void run()
        while (!Thread.interrupted())
            catch (InterruptedException e)

Спасибо за комментарии к теме)
  • ,

Учим английский (навыки чтения). Уровень 1.

Все мы учили English, как говорится, хоть где-нибудь и хоть как-нибудь.
Сам я в школе и институте прошляпил английский (хотя получил по нему отлично, так как помог в каникулы с ремонтом класса в школе — красил, шпаклевал и т.п., а в институте в лихие 90-е некоторым преподам было банально не до нас).

При трудоустройстве на должность программиста Вас скорее всего попросят перевести с английского часть текста или документации и пересказать прочитанное.

В конце данного топика я приведу классический текст адаптированной сказки «Кот в сапогах» Шарля Перро (куда же мы денемся без котиков). Вы должны его с листа читать как русский текст, так как:
  • словарный запас мал, соответствует уровню Starter/Elementary (Total words: 2665 Unique words: 560)
  • содержание текста, надеюсь, всем знакомо :)

Вероятно, пару-тройку незнакомых слов, могут встретить и люди со средним знанием english-а, так, что и им, возможно, будет полезно прочитать эпическую фентези про котэ-победителя гигантов.
Кому тяжело — учите встретившие слова и разбирайте грамматику.
Слова лучше заносить в онлайн-тренинги английского (я, например, предпочитаю, lingualeo.ru, который имеет plugin позволяющий заносить прямо из браузера, тыкнув на незнакомое слово) и тренировать там периодически. Аналогично многие сайты предлагают и тренинг грамматики.

Если интересно, могут периодически выкладывать и другие тексты (со временем и технические, возможно адаптированные). Чтобы JR-шовцы могли периодически тренировать навык перевода. Напишите в комментариях, стоит ли.

P.S. К администрации, текст сказки взят отсюда: english-e-books.net (graded readers ebooks – best choice to learn English. Download or read online for free! ), так что, думаю проблем с нарушением юрид прав нет.

Собственно текст.
Charles Perrault. Puss in boots.
Once upon a time there was a poor miller. He lived in a small house, together with his three sons. The miller worked at the mill, and his sons helped him. The miller had no horse. He used his donkey to bring wheat from the fields.
The years went by. The miller grew old and died. His sons decided to divide their father's things among themselves. That was easy: he had almost nothing to leave to his sons. Only his mill, his donkey and his cat.
«I'm going to take the mill,» said the miller's oldest son.
«I'm going to take the donkey,» said the second.
«And what about me?» asked the youngest son.
«You? You can take the cat,» laughed his brothers.
The young fellow was very much upset. He went out of the house and sat down on the bench.
«Oh, well,» he said in a sad voice. «My brothers have the mill and the donkey. They can put them together and make enough money to live an honest life. But what can I do? I can eat the cat, and I can
make a hat out of his fur. But then I have nothing. I can die of hunger.» The Cat was sitting on the bench too. He was trying not to listen to his master. But of course he heard all his words. And he didn't like them at all. He put on a serious face and said:
«Don't look so sad, Master. I'm not a bad thing. And I am more useful to you alive than dead. I can prove that.»
«How so?» asked the Cat's master. «All you have to do is to give me a bag, and get a pair of boots. Such as gentlemen wear in the woods. I'm going to show you that you're lucky to have me.»
«It's unusual that a cat can speak at all,» the miller's son said to himself. But then he started thinking. «This cat's very good at catching rats and mice. He played so many cunning tricks on them. He never came home without a rat or a mouse. He could hide in the wheat, or pretend to be dead. Perhaps, he can help me after all.»
«OK,» he said to the Cat. «I'm going now to order the boots.»

The miller's son went to the best shoemaker in town. The shoemaker made elegant shoes and boots for gentlemen.
«I want to order a fine pair of very small boots. They are for my cat,» said the young man.
«OK,» said the shoemaker.
He was not surprised at all. Or, perhaps, just a little.
«Do have any money?» he asked.
«Here you are,» said the miller's son.
He took his last silver coin out of his pocket and gave it to the shoemaker.
Soon the boots were made. The Cat pulled them on. He looked very nice in his elegant boots.
«Don't worry about the money, Master. I'm going to bring you luck,» said the Cat in Boots.
He put the bag around his neck. Cats have no hands, so he held the strings in his forepaws. Then he put some vegetables and a piece of bread into the bag.
The Cat went to the woods. There were many rabbits there. So he lay down, pretending to be dead. The
Cat didn't move at all. His plan was to wait for some foolish rabbit to come and look into his bag.
The Cat didn't wait long. Soon a foolish young rabbit put his head inside the bag. The Cat closed the strings at once and caught him. Then, very proud, he went with the bag to the palace and asked to speak with the King.
The King agreed to see the unusual visitor. The Cat went upstairs to the King's room. He came up to the King and made a low bow. Then he said:
«Sir, here is a nice rabbit from the lands which belong to my noble master, the Marquis of Carabas (he decided to give his young master this title). He told me to offer it to Your Majesty.»
«Tell your master,» said the King, politely, «that I thank him for this nice present. I'm very pleased with his attention.»
Another time the Cat went to a wheat field and hid among standing wheat. He again held his bag open. Soon two fat partridges ran into the bag. The Cat drew the strings, and caught them both.
The Cat went to the King's palace again. He gave the partridges to the King, with the same message from his master as before. The King received the gift. His majesty was very pleased. He even ordered to take the Cat down into the kitchen and give him something to eat and drink.
The Cat enjoyed the meal very much. He sat in the kitchen for a long time, talking about his rich master, the Marquis of Carabas.

The Cat in Boots continued for two or three months to bring presents to the King. Every time he came to the palace and said, «Your Majesty, here's another present from my master, the Marquis of Carabas.»
Then one day one of the Cat's friends in the palace said to him, «The King wants to drive today in his carriage along the bank of the river. His Majesty is going to take his daughter with him.»
The young princess was a very beautiful girl.
The Cat in Boots said to his master:
«Now you must do what I tell you.»
The miller's son knew nothing about the Cat's new plan. But he was sad and unhappy. That's why he agreed at once.
«Be it so,» he said. «Tell me about your plan.»
«I don't ask much,» said the Cat, looking wise, as cats can. «All you must do is to go and bathe in the river. I know a good place. Then leave the rest to me. Only remember that you are no longer yourself, but the Marquis of Carabas.»
«OK,» said the miller's son, «it's all the same to me.»
He went to the bank of the river, took off his clothes and went bathing. The Cat followed his master and hid his clothes under a great stone.
At that moment the King drove past that place in his carriage. The Cat began to shout at the top of his voice:
«Help! Help! The Marquis of Carabas is drowning!»
The King heard the shouts and put his head out of the carriage. He recognized the Cat.
«Guards!» he said. «Help the Marquis of Carabas! Quick!»
The guards ran to the river. They quickly pulled the young man out of the water.
The Cat came up to the King's carriage. He made a low bow and gave his explanations.
«My master went bathing,» he said, «and suddenly some thieves came. They took all his clothes and ran away. And now the Marquis of Carabas can't appear before Your Majesty and your beautiful daughter.»
«Oh, it's not a problem at all,» said the King.
He ordered one of his guards to ride back to the palace and bring fine clothes for the Marquis of Carabas.
Soon the guard brought a nice suit for the miller's son. The young man put it on and came up to the carriage to thank his majesty.
The miller's son wasn't rich, but he was a handsome and well-built fellow. In the King's elegant suit he looked like a real gentleman.
The beautiful princess admired the handsome young man very much. The miller's son looked at the girl several times, and she fell in love with him.
The King was very happy to meet the Marquis of Carabas. He asked the young gentleman to sit with him and his daughter in the carriage. Of course, the miller's son didn't refuse.

The Marquis of Carabas entered the carriage. The Cat in Boots ran away fast. He kept a long way ahead of the King's carriage. He went on and on, till he saw some mowers in a meadow. The Cat came up to them.
«Listen, good people,» he said, in a very firm voice, «the King is going to stop here and talk to you. You must tell him that this meadow belongs to the Marquis of Carabas. Do that if you want to stay alive.»
The King's carriage drove up to the meadow.
«What a nice meadow, and so much hay! Whose meadow is this?» he asked the mowers.
«It belongs to the Marquis of Carabas, sir,» they all cried with one voice, trembling with fear.
«You have a good meadow, marquis,» said his majesty to the miller's son.
The young man bowed and said, «As you see for yourself, this is a very good meadow, sir. The crops of hay are high every year.»
The Cat went still on. He was far ahead of the King and his companions. Finally he came to a wheat field. There were some reapers on the field.
«My good fellows,» he said to the reapers, «the King is going to stop here and talk to you. You must tell him that this field belongs to the Marquis of Carabas. Do that if you want to stay alive.»
The King's carriage arrived a few moments later.
«What a beautiful wheat field! Good people, whose field is this?» he asked the reapers.
«It belongs to the Marquis of Carabas, sir,» cried the reapers, trembling with fear.
At this the King was pleased with the Marquis more than ever.
The King continued his journey, and the Cat still ran on ahead of him. He said the same thing to everyone. The King drove past a new mill, a beautiful garden, houses, more fields and meadows. And all the people on his way said the same: all those places belonged to the Marquis of Carabas.
Finally the Cat returned to the King. He came up to the carriage and bowed.
«Your master is a very rich man,» said the King to the Cat. Then he smiled to the young man and said, «My dear Marquis, isn't this your castle in that park? It looks beautiful. Can we go there now?»
The miller's son didn't know what to say. He looked at the Cat. The Cat bowed and said:
«My master, the Marquis of Carabas, is happy to invite you to the castle. But, Your Majesty, please wait an hour. I'm going to the castle at once to get everything ready for you.»
«No problem,» said the King. «And in the meantime we can visit your nice park. My dear Marquis,» he said to the young man, «I hope you have many flowers there. My daughter is so fond of white roses.»
The Cat in Boots ran to the castle. It stood in the middle of a big park. There were wonderful flowers everywhere in the park.
The castle itself was a beautiful high building with small towers. The roofs were red. The walls of the castle were made of white stone. The windows were narrow but high. The rooms on the ground floor had the highest windows. And through the glass visitors could see elegant green curtains.
The castle belonged to a giant. He was the richest giant in the country. All the fields, meadows and woods around the castle were part of his lands. Many people worked for him.
The Cat already knew a lot about the Giant. He was a cruel man. Everyone was terribly afraid of him.
The Cat put on a brave face and went to the castle with his boots on. Soon he arrived at the gate. He asked a servant to speak to the Giant.
«I am a traveller,» he said, «I was not far from here. I couldn't go so near the castle of such a noble gentleman without meeting him.»
The Giant heard this message and agreed to see the visitor. He was going to have dinner, so he was in a good mood.
«Please sit down and have dinner with me,» he said to the Cat.
«Thank you, sir,» said the Cat. «But first I hope you can answer a question. They say that you can change yourself into any animal. A lion, for example, or an elephant.»
«That's true,» said the Giant. «And I can prove it just now. Look! Whom do you see now?»
And the Giant changed himself into a big lion.
The Cat was terribly frightened. He even climbed up the curtain. Of course, it wasn't easy to climb in boots. But the lion was so big! How can you be brave and keep still near such an awful animal?
A few moments later the lion changed back into the Giant. The Cat came down.
«I'm so sorry, sir. I was very frightened,» he said. «But do you know what I think? It was easy for such a big gentleman as you to change yourself into a large animal. But I'm afraid even you can't become a small animal, such as a rat or a mouse. It's just impossible.»
«Impossible!» cried the Giant, very angry. «See how it's impossible!»
At the same moment he changed himself into a mouse. The mouse began to run about the floor.
It was part of the Cat's plan. He jumped on the mouse at once and ate it. So that was the end to the Giant.

Meanwhile the King, his daughter and the Marquis of Carabas arrived at the castle. The carriage drove over the drawbridge with a loud noise. The Cat heard the noise and ran out into the yard to meet the visitors.
«Welcome, sir, to the castle of the Marquis of Carabas,» he said in a loud voice.
«Your castle is so beautiful, Marquis,» said the King. «Nothing could be finer than this yard and all these buildings. It's not a castle at all. It's a real palace. Let's go inside and look around, if you don't mind.»
The King got out of the carriage and went to the door. The Marquis, without speaking, gave his hand to the princess. As soon as she got out of the carriage, they followed the King.
The King and his companions went through several beautiful rooms and came into a great hall. In the middle of the hall they saw a long table. It was ready for dinner. There were a lot of wonderful things on the table. All of them were the Giant's favourite dishes.
«Why don't we have dinner now?» said the Marquis. «Please sit down.»
The guests took their places. Everyone was hungry, so the dinner started at once.
The King was happy. His daughter was happy too. The girl, in fact, was very much in love with the handsome and polite young man.
His majesty was a practical man, too.
«The marquis is a noble gentleman. My daughter likes him, and he's rich. I think he can make a good husband for my daughter,» he thought after his sixth or seventh glass of wine.
Soon the dinner was over. The King looked across the table at the miller's son.
«Do you like my daughter, marquis?» he said.
«Yes, sir,» said the young man.
«You can marry her then. If you want, of course,» said the King. «That's your choice.»
«I am happy to do that,» said the Marquis of Carabas.
The princess's happy eyes said the same.
The miller's son married the King's daughter the next day. The young man was happy. He was a rich noble gentleman now. The Giant's castle belonged to him. He had all the Giant's lands, too. And he had a beautiful wife.
The Cat in Boots became at once a great lord. Of course, he stayed in the castle with the marquis and the princess. He ordered more elegant boots for himself. But he never ran after mice any more, except for pleasure.

Типичные ошибки начинающих программистов

Не так давно пробовал устраиваться на работу тестировщиком Java(мой текущий уровень — 19). Получил следующий фидбек:

К сожалению, есть ошибки в задании. Ниже фидбек от нашего специалиста:

Неявная логика в методах
Отсутствие иерархии, неумение сравнивать объекты по типу
Недостаточное знакомство с базовыми вещами в Java
Исользование громоздких конструкторов вида CLEANER (false, false, true, false, false, false, false)
Спагетти-код там, где можно было упростить логику

Соль в том, что моя программа выполняет все требования. которые были описаны в ТЗ. Для ее описания мне хватило тех знаний Java, которые на данный момент есть. Но не хватило чего-то другого. Как с этим бороться? Может, я делаю что-то не так? Мне стоит что-то перечитать или что-то сделать? Моя проблема, как и многих начинающих программистов, не в том, что я чего-то не знаю, а что не умею обращаться с тем, что знаю. Все задачи решал до этого, серьезных проблем не возникало.

Если кому-то интересен мой код — github.com/vozni4iy/office
  • ,

Немного вопросов по нитям с собственными примерами.

Создал класс
SomeThread implements Runnable
В нем один метод
добавляющий букву к строке и выводящий строки на консоль. Метод вызывается через
пометить synchronized, то вывод стабильно такой:
a-b Thread-1
aa-bb Thread-0

А если без synchronized (как в коде ниже), то выводит, кроме прочих вариантов и так:
a-b Thread-1
a-b Thread-0
Не могу понять почему так происходит. Получается, что одна из нитей не выполняет операцию
s1 +=
s2 +=
Кто поможет разобраться в этом конкретном примере? Заранее спасибо)

public class TestThread
    public static void main(String[] args)
        SomeThread someThread = new SomeThread();

        Thread thread1 = new Thread(someThread);
        Thread thread2 = new Thread(someThread);


class SomeThread implements Runnable

    String s1 = "";
    String s2 = "";

    public void run()
        catch (IOException e)

    void incrementString() throws IOException
        s1 += "a";
        s2 += "b";
        System.out.println(s1+ "-" + s2 + " " + Thread.currentThread().getName());

Синхронизация и её корректное использование.

Мини введение.
Убился, решая две бонусные задачи CrUD 17 лвла. Готов был задушить составителей этих задач, но оба раза не принималось по моей вине (тупо забывал убрать код для тестирования кода :)). Так что, разрабы, извините, если что, проклятия с вас снял)) Но не об этом сейчас…

Хочется с людьми поспорить на тему: какие методы нуждаются в синхронизации, в синхронизации по классу или его объекту или вообще по чему-нибудь ещё))) Проштудировал лекции 17 уровня, читал главу про трэды Эккеля (ну и мудрёно пишет, философ), но мог что пропустить, поэтому не сильно пинайте) Для примера возьмём ту самую бонусную задачу CrUD Batch. Код не ищите, всё нужное сейчас здесь будет))

Есть там список, поле класса:
public static List<Person> allPeople = new ArrayList<Person>();

Не вдаваясь в подробности, скажу, что список редактируется числом методов (ну или просто используется ими). Начал я вроде как книгу писать, но в принципе на этом повествование заканчивается. Вот вам эти методы, прошу объяснить, какие из них и как нужно синхронизировать (ну или хотя бы ткните в какую-нибудь ссылку носом))).

public static void create(String name, String sex, String bd) throws ParseException
        if (sex.equals("м")) allPeople.add(Person.createMale(name, inFormat.parse(bd)));
        else if (sex.equals("ж")) allPeople.add(Person.createFemale(name, inFormat.parse(bd)));

        System.out.println(allPeople.size() - 1);

    public static void update(int id, String name, String sex, String bd) throws ParseException
        if (sex.equals("м"))
        } else if (sex.equals("ж"))

    public static void delete(int id)

    public static void info(int id)
        System.out.println(allPeople.get(id).getName() + (allPeople.get(id).getSex().equals(Sex.MALE) ? " м " : " ж ") + outFormat.format(allPeople.get(id).getBirthDay()));
  • ,

Как выйти на иностранного заказчика?

Здесь учится много людей. И каждый задумывается над применением полученных знаний. А есть и те, кто уже имеет практический опыт. Хотелось бы узнать как получить бесценный опыт работы с иностранными заказчиками. Для начала деньги не важны, нужен именно опыт и знания. Естественно, большим камнем преткновения становиться знание иностранного языка. Достаточно ли уметь писать и читать на английском. Либо без разговорного английского не обойтись? Может у кого-то есть реальные примеры начала работы с зарубежными работодателями через интернет? Спасибо за любую информацию. Ведь на просторах постсоветского пространства не всегда легко найти работы, особенно если город не очень большой.

WEGAME – главное событие играющей Украины

Интересное мероприятие от наших партнеров

16-17 апреля 2016 года в Киеве состоится международная фестиваль интерактивных развлечений WEGAME. Каждый поклонник виртуальных миров и электронных развлечений уже запасается билетами!

WEGAME – это настоящий рай для фаната видеоигр! Здесь можно увидеть самые свежие компьютерные и консольные игры, поиграть в них, подержать в руках долгожданные мобильные хиты, перекинуться парой слов с настоящими живыми разработчиками и побывать на презентации всех тех проектов, что заставляют геймеров страдать от бессонницы и мучиться от нетерпения. WEGAME – это всё самое-самое! Самые яркие презентации, самые увлекательные конкурсы, самые красивые девушки-промоутеры, самые напряжённые турниры, самые крутые призы и всё то, что греет сердце любого фаната интерактивных развлечений!

Именно на WEGAME впервые в Украине будут представлены последние новинки ведущих отечественных и зарубежных компаний. Воспользуйтесь шансом увидеть, пощупать и поиграть в главные проекты игровой индустрии задолго до того, как они попадут в руки игроков! Зачем смотреть трейлеры на YouTube, если можно прийти на выставку и поиграть?

Гостей WEGAME ожидает погружение в VR-реальность посредством новейших очков, масштабная презентация консольных новинок, демонстрационные стенды, на которых посетители смогут опробовать последние достижения компьютерной техники и самые новые мобильные устройства!

Фанаты киберспорта в течение WEGAME смогут лично наблюдать за соревнованиями любимых отечественных и зарубежных команд Высшей лиги. Самые удачливые и настырные смогут пообщаться с людьми, которые сделали себе имя в мире прогейминга, и получить советы и мастер-классы от «звёзд».

Гости выставки смогут купить самые новые игры, геймпады, профессиональные игровые мыши и другое важное для каждого игрока оборудование по специальным ценам! Фанатам поп-культуры представится возможность отовариться сувенирами, статуэтками любимых персонажей фильмов и игр, а также другими интересными штуковинами – никто не уходит с WEGAME с пустыми руками!

Фанаты косплея, мастера перевоплощения и люди, способные отличить Гульдана от Артаниса, смогут показать себя во всей красе и посмотреть на красу других. В рамках специальной программы WEGAME приглашает всех косплееров представить свои самые любимые образы и самые лучшие работы в кругу единомышленников. Здесь вас оценят по достоинству!

Не пропустите! 16-17 апреля 2016-го, НСК «Олимпийский». Главное событие года в мире игр. Приходите – не пожалеете!
Прямо сейчас на нашем сайте можно узнать, как идёт подготовка к событию, и поделиться впечатлениями: wegame.com.ua/.

Присоединяйтесь к нашим официальным группам в социальных сетях: FB и ВК.

Контакты организаторов:
+38 044 392 06 96