You are on page 1of 6

EX NO: 6A

MULTITHREADING IN JAVA
DATE:

AIM:
To write a Java program to create three threads. The first thread should print the values from
1 to 10. The second thread should print the values 11 to 20 and the third thread should print
values from 21 to 30.

ALGORITHM:

PROGRAM:

class Values
{

synchronized void printNum(int n)


{

for(int i=n;i<n+10;i++)
{

System.out.print(" " + i);

try
{

Thread.sleep(100);

}
catch(Exception e)
{
System.out.println(e);
}
}
}
}

class MyThread1 extends Thread


{
Values n;
MyThread1( Values obj)
{
n = obj;
}
public void run()
{
n.printNum(1);
System.out.println(" -> thread 1");
}
}
class MyThread2 extends Thread
{

Values n;

MyThread2(Values num)
{

n=num;

}
public void run()
{
n.printNum(11);
System.out.println(" -> thread 2 ");
}
}
class MyThread3 extends Thread
{
Values n;

MyThread3(Values num)
{

n=num;

}
public void run()
{
n.printNum(21);
System.out.println(" -> thread 3 ");
}
}

public class javaprog


{

public static void main(String args[])


{
Values num = new Values();

MyThread1 t1=new MyThread1(num);


MyThread2 t2=new MyThread2(num);
MyThread3 t3=new MyThread3(num);
t1.start();
t2.start();
t3.start();
}
}

OUTPUT:

RESULT:
For the above program, the output was verified successfully.
EX NO: 6B
DEPOSIT AND WITHDRAWAL FUNCTIONS OF A BANK
DATE:

AIM:
To Write a Java program to write methods for deposit and withdrawal functions of a bank.
The methods should be synchronized in such a way when a user is depositing the amount, the
withdrawal should not occur.

ALGORITHM:

PROGRAM:

class Customer
{

int amount=12000;

synchronized void withdraw(int with_amt)


{

System.out.println("going to withdraw...");

if(with_amt>amount)
{

System.out.println("Less balance!! waiting for deposit...");

try
{
wait(); // causes a thread to wait until it is notified.
}
catch(Exception e)
{
System.out.println(e);
}

}
amount=amount - with_amt;

System.out.println("withdraw completed. BALANCE = "+amount);

synchronized void deposit(int dep_amt)


{

System.out.println("Going to deposit...");
amount = amount + dep_amt;

System.out.println("Deposit completed. BALANCE = "+amount);

notify(); // unblocks the thread that called wait on this object.

}
}

class oops
{

public static void main(String args[])


{

final Customer c=new Customer();

Thread t1=new Thread()


{

public void run()


{
c.withdraw(15000);
}

};

Thread t2=new Thread()


{

public void run()


{
c.deposit(9000);
}

};
t1.start();
t2.start();
}
}
OUTPUT:

RESULT:
For the above program, the output was verified successfully.

You might also like