Just started practicing multithreading. I came up with my own task:
It is a cup, completely filled with water. Every 3 seconds they drink 10% of the liquid. And every 6 seconds, pour 10% of the liquid. Draw it programmatically and calculate after how many seconds the cup will be empty.
I first implemented it in two cycles, but I realized that this is not what I need. As I understand it, there must be two streams living independently of each other. I have never done this and I did not succeed. I ask for help
Everything works fine at first, but as soon as the flow of drink empties the cup, the plus stream helps it to fill.
public class Main { static int cap = 100; static int time = 0; static Thread plus; public static void main(String[] args) throws InterruptedException { Thread drink = new Thread(new Runnable(){ @Override public void run() { while (cap > 0) { try { Thread.sleep(3000); } catch (InterruptedException e) {} cap -= 10; System.out.println(cap); time += 3; } Thread.currentThread().interrupt(); plus.interrupt(); System.out.println(time); } }); plus = new Thread(new Runnable(){ @Override public void run() { while (cap > 0) { try { Thread.sleep(6000); } catch (InterruptedException e) {} cap += 10; System.out.println(cap); time += 6; } Thread.currentThread().stop(); } }); drink.start(); plus.start(); } }
lock(Object);- ArchDemonstop(); - deprecated !!! Never use this method! It leads to unpredictable consequences. - Oleksiy Morenetsinterrupt(), but nowhere check the interrupt state of the thread. - Oleksiy Morenetssynchronized void add(),synchronized void drink()- Oleksiy Morenetstime += 3 + 3, the second thread will maketime += 6. Total it turns out that 12 seconds have passed, which contradicts the initial conditions. The second assumption: let's say from a full mug drank and then poured. We consider 100 - 100 * 0.1 = 90, 90 + 90 * 0.1 = 99. You also get 100. - ArchDemon