I do not know how to prioritize tasks here. I know that cats should make birth first, kittens go out of basket and last is brining kittens back to basket. Problem is that I do not know how to use join to do that. I know that join makes a Thread wait for other thread to finish. Please let me know how it works.
How let's say I have 4 threads:
thread1
thread2
thread3
thread4
How can I set threads as list: 2,4,1,3
thread2.join;
thread4.join;
thread1.join;
thread3.join;
???
I have resolved this task but I do not understand how it works.
I thought that maybe if thread is in main method it is prioritized but when I did cat1.join and cat2.join second cat randomly gave birth first or let kittens from cat1 go out of basket
package pl.codegym.task.task16.task1610;
/*
Przyporządkowywanie wywołań do join()
*/
public class Solution {
public static void main(String[] args) throws InterruptedException {
Cat cat1 = new Cat("Misia");
Cat cat2 = new Cat("Coco");
}
private static void investigateWorld() {
try {
Thread.sleep(200);
}
catch (InterruptedException e) {
System.out.println(e);
}
}
public static class Cat extends Thread {
protected Kitten kitten1;
protected Kitten kitten2;
public Cat(String name) {
super(name);
kitten1 = new Kitten("Kociak 1 (matka - " + getName() + ")");
kitten2 = new Kitten("Kociak 2 (matka - " + getName() + ")");
start();
}
public void run() {
System.out.println(getName() + " urodziła 2 kocięta");
try {
initAllKittens();
} catch (InterruptedException e) {
}
System.out.println(getName() + ": Wszystkie kocięta są w koszyku. " + getName() + " przyniosła je z powrotem");
}
private void initAllKittens() throws InterruptedException {
kitten1.start();
kitten2.start();
kitten1.join();
kitten1.join();
}
}
public static class Kitten extends Thread {
public Kitten(String name) {
super(name);
}
public void run() {
System.out.println(getName() + " wyszedł z koszyka");
investigateWorld();
}
}
}