Showing posts with label Threads. Show all posts
Showing posts with label Threads. Show all posts

InterThread Communication in java

InterThread Communication in java
SOURCE : Customer.java






class Customer {

int amount = 100;

synchronized void withdraw(int amount) {
System.out.println("going for withdraw please be patience ....");
if (this.amount > amount) {

System.out.println("doesn`t have balance please wait....");
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

this.amount -= amount;

System.out.println("balaced amount " + amount);

}

synchronized void deposit(int amount) {
System.out.println("amount going for deposited");
this.amount += amount;
notify();
}

}

public class InterThreadCommunication {

public static void main(String[] args) {

final Customer c = new Customer();
try {
c.withdraw(200);
c.deposit(300);
} catch (Exception e) {
// TODO: handle exception
}

}

}



INPUT




OUTPUT

going for withdraw please be patience ....
balaced amount 200
amount going for deposited








Sandeep Kumar D

Hi, I have written and developed this post so that most of people will be benefited. I'm committed to provide easy and in-depth tutorials on various technologies.I hope it will help you a lot.

- Sandeep Kumar D

Follow Me @Google+




How to print even and odd numbers using threads in java

Now a day's, a common question asked in interviews are threads. In this post we are going to learn how to implement two thread which is usedto display odd and even numbers.

In the following program, thread 1 prints even numbers and thread 2 prints odd numbers

SOURCE : EvenOddPrinter.java

package com.becbe.threads;

public class EvenOddPrinter implements Runnable {

boolean isEven = false;
Object lock;

public EvenOddPrinter( boolean isEven, Object lock) {
this.isEven = isEven;
this.lock = lock;
}

@Override
public void run() {
System.out.println("Inside Run");
if(isEven) {
printEven();
} else {
printOdd();
}

}

private void printOdd() {
synchronized (lock) {
for (int i = 1; i < 100;) {
lock.notify();
i = i + 2;
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lock.notify();
System.out.println( i );
}
}
}


private void printEven() {
synchronized (lock) {
lock.notify();
for (int i = 0; i < 100;) {
i = i + 2;
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lock.notify();
System.out.println( i );
}
}

}

public static void main(String[] args) {
Object lock = new Object();
Thread t1 = new Thread(new EvenOddPrinter(true, lock));
Thread t2 = new Thread(new EvenOddPrinter(false, lock));
t1.start();
t2.start();
}

}









Thulasiram P

Hi, I have written and developed this post so that most of people will be benefited. I'm committed to provide easy and in-depth tutorials on various technologies.I hope it will help you a lot.

- Thulasiram P

Follow Me @Google+