public class Belajar1 {
public Integer total = 0;
public static void main(String[] args) {
Belajar1 e1 = new Belajar1();
e1.doStuff();
}
public void doStuff() {
System.out.println("pertama kali mulai");
synchronized (total) {
System.out.println("mulai lagi");
A a = new A(this);
a.start();
try {
total.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Total=" + total);
}
}
}
class A extends Thread {
private Belajar1 belajar1;
public A(Belajar1 e) {
belajar1 = e;
}
public void run() {
synchronized (belajar1.total) {
for (int i = 0; i < 10; i++) {
belajar1.total += i;
}
belajar1.total.notify();
}
}
}
Contoh 2 Program java IllegalcMonitor State Exception
class NotifyLab
{
static class Rendezvous
{
synchronized public void hurryUpAndWait()
{
System.out.println("*****-------****");
try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
}
synchronized public void not()
{
Thread.currentThread().notify();
}
}
static class Waiter extends Thread
{
Rendezvous r;
public Waiter(Rendezvous r,String name)
{
super(name);
this.r =r;
}
public void run()
{
r.hurryUpAndWait();
System.out.println(Thread.currentThread().getName()+" Notified");
}
}
public static void main(String[] args)
{
Rendezvous r = new Rendezvous();
Waiter wt[] = new Waiter[5];
for(int i=0;i<=4;i++)
{
wt[i] = new Waiter(r,"Thread "+(i+1));
wt[i].start();
}
r.not();
}
}
Tidak ada komentar:
Posting Komentar