Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Resourse {
- private int res = 0;
- private boolean isReady = false;
- synchronized void put(int res) {
- while (isReady)
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("Положили: " + res);
- this.res = res;
- isReady = true;
- notifyAll();
- }
- synchronized void get() {
- while (!isReady)
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("Забрали: " + res);
- isReady = false;
- notifyAll();
- }
- }
- class Producer implements Runnable {
- Resourse resourse;
- Producer(Resourse resourse) {
- this.resourse = resourse;
- }
- public void run() {
- int i = 0;
- while (true) {
- resourse.put(i++);
- }
- }
- }
- class Customer implements Runnable {
- Resourse resourse;
- Customer(Resourse resourse) {
- this.resourse = resourse;
- }
- public void run() {
- while (true) {
- resourse.get();
- }
- }
- }
- public class Test {
- public static void main(String args[]) throws Exception {
- Resourse resourse = new Resourse();
- Producer producer = new Producer(resourse);
- Customer customer = new Customer(resourse);
- Thread thread1 = new Thread(producer);
- Thread thread2 = new Thread(customer);
- thread1.start();
- thread2.start();
- Thread.sleep(1000);
- System.exit(0);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement