Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.j256.resource;
- /**
- * Little example of thread resource contention.
- */
- public class Person implements Runnable {
- private final int id;
- private final String resourceName;
- private final Resource resource;
- long enjoyCount;
- public static void main(String[] args) {
- Resource resource = new Resource();
- Thread t1 = new Thread(new Person(1, "paper", resource));
- Thread t2 = new Thread(new Person(2, "toy", resource));
- Thread t3 = new Thread(new Person(3, "food", resource));
- t1.start();
- t2.start();
- t3.start();
- }
- public Person(int id, String resourceName, Resource resource) {
- this.id = id;
- this.resourceName = resourceName;
- this.resource = resource;
- }
- public void enjoys() {
- try {
- Thread.sleep(1);
- enjoyCount++;
- if (enjoyCount % 1000 == 0) {
- System.out.println("Person " + id + " enjoyed " + enjoyCount);
- }
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- return;
- }
- }
- public void run() {
- while (true) {
- try {
- // this sleep makes it a little bit far otherwise the thread that called notify tends to reacquire
- // the lock immediately
- Thread.sleep(1);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- return;
- }
- resource.takesResource(this);
- enjoys();
- resource.signal(this);
- }
- }
- public static class Resource {
- boolean paper;
- boolean toy;
- boolean food;
- public synchronized void takesResource(Person person) {
- if ("paper".equals(person.resourceName)) {
- while (toy || food) {
- try {
- wait();
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- return;
- }
- }
- toy = true;
- food = true;
- } else if ("toy".equals(person.resourceName)) {
- while (food || paper) {
- try {
- wait();
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- return;
- }
- }
- food = true;
- paper = true;
- } else if ("food".equals(person.resourceName)) {
- while (paper || toy) {
- try {
- wait();
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- return;
- }
- }
- paper = true;
- toy = true;
- } else {
- System.exit(1);
- }
- }
- public synchronized void signal(Person person) {
- if ("paper".equals(person.resourceName)) {
- toy = false;
- food = false;
- } else if ("toy".equals(person.resourceName)) {
- food = false;
- paper = false;
- } else if ("food".equals(person.resourceName)) {
- paper = false;
- toy = false;
- } else {
- System.exit(1);
- }
- notifyAll();
- }
- }
- }
Add Comment
Please, Sign In to add comment