Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Manage {
- private Object lock = new Object();
- private LinkedList<Integer> intStorage = new LinkedList<Integer>();
- private LinkedList<Integer> evens = new LinkedList<>();
- private LinkedList<Integer> odds = new LinkedList<>();
- public void intCollection() throws InterruptedException {
- for (int i = 0; i < 20; i++) {
- synchronized(lock) {
- while(i == m) {
- lock.wait();
- }
- intStorage.add(i);
- LocalLock.notifyAll();
- System.out.println(intStorage);
- }
- Thread.sleep(100);
- }
- }
- public void evens() throws InterruptedException {
- for(int i = 0; i < intStorage.size() ; i++) {
- synchronized(lock) {
- if(intStorage.get(i) % 2 != 0) {
- lock.wait();
- }
- if(intStorage.get(i) % 2 == 0) {
- int j = intStorage.remove(i);
- evens.add(j);
- lock.notifyAll();
- }
- System.out.println(evens);
- }
- Thread.sleep(1000);
- }
- }
- public void odds() throws InterruptedException {
- for(int i = 0; i < intStorage.size() ; i++) {
- synchronized(lock) {
- if(intStorage.get(i) % 2 == 0) {
- lock.wait();
- }
- if(intStorage.get(i) % 2 != 0) {
- int j = intStorage.remove(i);
- odds.add(j);
- lock.notifyAll();
- }
- System.out.println(odds);
- }
- Thread.sleep(1000);
- }
- }
- public static void main(String[] args) throws InterruptedException {
- Manager m = new Manager();
- Thread t1 = new Thread(){
- public void run() {
- try {
- m.intCollection();
- } catch (InterruptedException e) {
- }
- }
- };
- Thread t2 = new Thread(){
- public void run() {
- try {
- m.evens();
- } catch (InterruptedException e) {
- }
- }
- };
- Thread t3 = new Thread(){
- public void run() {
- try {
- m.odds();
- } catch (InterruptedException e) {
- }
- }
- };
- t1.start();
- t2.start();
- t3.start();
- t1.join();
- t2.join();
- t3.join();
- }
Add Comment
Please, Sign In to add comment