Define two threads such that one thread should
print even numbers and another thread should
print odd numbers.
class Even extends Thread{
public void run(){ class TestThread
for(int i=2;i<10;i++){ {
if(i%2==0){ public static void main(String args[])
System.out.println("Even="+i); {
yield();
} Even e1=new Even();
} Odd o1=new Odd();
Thread t1=new Thread(e1);
}
Thread t2=new Thread(o1);
}
class Odd extends Thread{ t1.start();
public void run(){ t2.start();
for(int i=2;i<10;i++){ }
if(i%2!=0){ }
System.out.println("odd="+i);
yield();
}
}
}
}
• Modify the Account class to implement
synchronization concept.
class Account3 extends Thread{
int accno;
float balance;
float amount;
Account3(int ano,float bal,float withdrawAmount) {
accno=ano;
balance=bal;
amount=withdrawAmount;
}
synchronized public void withdraw() {
System.out.println("Trying to withdraw Rs."+amount);
System.out.println("Getting the balance:"+"\nbalance="+balance);
if(balance>=amount) {
System.out.println("please collect the cash:"+amount);
try {
Thread.sleep(1500);
}
catch(InterruptedException e) { }
balance=balance-amount;
}
else
System.out.println("Insufficient funds");
System.out.println("A/C balance is updated to Rs."+balance);
}
public void run()
{
withdraw();
}}//Account3 class ThreadSyncB
{
public static void main(String args[])
{
Account3 a1=new Account3(1001,6000,5000);
Account3 a2=new Account3(1002,6000,5000);
Thread t1=new Thread(a1);
Thread t2=new Thread(a2);
t1.start();
t2.start();
}
}
• Write a program to implement thread priority
class Demo extends Thread
{
public void run()
{
System.out.println("max priority :"+MAX_PRIORITY);
System.out.println("min priority :"+MIN_PRIORITY);
System.out.println("normal priority :"+NORM_PRIORITY);
}
}
class ThprDemoD
{
public static void main(String args[])
{
Demo obj=new Demo();
obj.setPriority(Thread.NORM_PRIORITY);
obj.start();
}
}
class Demo extends Thread
{
public void run()
{
for(int i=1;i<=3;i++)
{
System.out.println(getName()+" "+i);
}
}
}
class ThprDemoS
{
public static void main(String args[])
{
Demo obj=new Demo();
Demo obj1=new Demo();
Demo obj2=new Demo();
obj.setPriority(Thread.MAX_PRIORITY);
obj1.setPriority(Thread.MIN_PRIORITY);
obj2.setPriority(Thread.NORM_PRIORITY);
obj.start();
obj1.start();
obj2.start();
}
}