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[])
[Link]("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{ [Link]();
public void run(){ [Link]();
for(int i=2;i<10;i++){ }
if(i%2!=0){ }
[Link]("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() {
[Link]("Trying to withdraw Rs."+amount);
[Link]("Getting the balance:"+"\nbalance="+balance);
if(balance>=amount) {
[Link]("please collect the cash:"+amount);
try {
[Link](1500);
}
catch(InterruptedException e) { }
balance=balance-amount;
}
else
[Link]("Insufficient funds");
[Link]("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);
[Link]();
[Link]();
}
}
• Write a program to implement thread priority
class Demo extends Thread
{
public void run()
{
[Link]("max priority :"+MAX_PRIORITY);
[Link]("min priority :"+MIN_PRIORITY);
[Link]("normal priority :"+NORM_PRIORITY);
}
}
class ThprDemoD
{
public static void main(String args[])
{
Demo obj=new Demo();
[Link](Thread.NORM_PRIORITY);
[Link]();
}
}
class Demo extends Thread
{
public void run()
{
for(int i=1;i<=3;i++)
{
[Link](getName()+" "+i);
}
}
}
class ThprDemoS
{
public static void main(String args[])
{
Demo obj=new Demo();
Demo obj1=new Demo();
Demo obj2=new Demo();
[Link](Thread.MAX_PRIORITY);
[Link](Thread.MIN_PRIORITY);
[Link](Thread.NORM_PRIORITY);
[Link]();
[Link]();
[Link]();
}
}