Created
May 30, 2019 06:31
-
-
Save draganczukp/157a57cafcf96f89612a2ef6a38734b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Random; | |
import java.util.concurrent.ArrayBlockingQueue; | |
import static java.lang.Thread.sleep; | |
public class Main { | |
static class W1 extends Thread{ | |
private final ArrayBlockingQueue<Integer> kolejka; | |
Random random; | |
public W1(ArrayBlockingQueue<Integer> kolejka){ | |
random = new Random(System.currentTimeMillis()); | |
this.kolejka = kolejka; | |
} | |
@Override | |
public void run() { | |
while (true){ | |
kolejka.add(random.nextInt(100)); | |
try { | |
sleep(Math.abs(random.nextLong() % 100)); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
static class W2 extends Thread { | |
private final ArrayBlockingQueue<Integer> kolejka2; | |
private final ArrayBlockingQueue<Integer> kolejka1; | |
private final Random random; | |
public W2(ArrayBlockingQueue<Integer> kolejka1, ArrayBlockingQueue<Integer> kolejka2){ | |
this.kolejka1 = kolejka1; | |
this.kolejka2 = kolejka2; | |
this.random = new Random(System.currentTimeMillis()); | |
} | |
@Override | |
public void run() { | |
while (true){ | |
try { | |
int l = kolejka1.take(); | |
l *= 2; // Jakieś działanie | |
kolejka2.add(l); | |
sleep(Math.abs(random.nextLong() % 100)); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
static class W3 extends Thread { | |
private final ArrayBlockingQueue<Integer> kolejka; | |
private final Random random; | |
public W3(ArrayBlockingQueue<Integer> kolejka){ | |
this.kolejka = kolejka; | |
this.random = new Random(System.currentTimeMillis()); | |
} | |
@Override | |
public void run() { | |
while (true){ | |
try { | |
int l = kolejka.take(); | |
System.out.println(l); | |
sleep(Math.abs(random.nextLong() % 100)); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
public static void main(String[] args) { | |
ArrayBlockingQueue<Integer> k1 = new ArrayBlockingQueue<>(20), k2 = new ArrayBlockingQueue<>(20); | |
Random random = new Random(System.currentTimeMillis()); | |
new W1(k1).start(); | |
new W2(k1, k2).start(); | |
new W3(k2).start(); | |
new Thread( ()->{ | |
while(true) { | |
try { | |
System.out.println(String.format("K1: %d, K2: %d", k1.size(), k2.size())); | |
sleep(1000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
}).start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
dzięki, działa