Thread Lab Assignment
Thread Lab Assignment
import java.io.*;
public class Program1
{
public static void main(String args[])throws Exception
{
Thread t1 = new Thread();
Thread t2 = new Thread();
for(int i = 0 ; i<20 ; i=i+2)
{
t1.sleep(100);
System.out.print("\n\t"+i);
}
for( int i = 0 ; i<10 ; i++ )
{
t2.sleep(100);
System.out.print("\n\t Pratik");
}
}
}
Q.2. Write a program to implement the concept of threading by
extending Thread Class and also by implementing interfaces.
Ans:
import java.io.*;
class ExtendThread extends Thread implements Runnable
{
public void run()
{
for( int i = 0 ; i<10 ; i++)
{
try
{
System.out.print("\n\n\t\t Extending Thread...!"+i);
Thread.sleep(100);
}
catch(Exception e)
{}
}
}
}
class ImplementThread implements Runnable
{
public void run()
{
for( int i = 0 ; i<10 ; i++)
{
try
{
System.out.print("\n\n\t\t Implementing Thread...!"+i);
Thread.sleep(100);
}
catch(Exception e)
{}
}
}
}
public class Program2
{
public static void main(String args[])
{
ExtendThread t1 = new ExtendThread();
ImplementThread t2 = new ImplementThread();
t1.start();
t2.run();
}
}
Q.3. Write a program to set the priority of two above threads and
check which thread executes first.
Ans: import java.io.*;
class ExtendThread extends Thread implements Runnable
{
public void run()
{
for( int i = 0 ; i<10 ; i++)
{
try
{
System.out.print("\n\n\t\t Extending Thread...! "+i);
Thread.sleep(100);
}
catch(Exception e)
{}
}
}
}
class ImplementThread implements Runnable
{
public void run()
{
for( int i = 0 ; i<10 ; i++)
{
try
{
System.out.print("\n\n\t\t Implementing Thread...! "+i);
Thread.sleep(100);
}
catch(Exception e)
{}
}
}
}
public class Program3
{
public static void main(String args[])
{
ExtendThread t1 = new ExtendThread();
ImplementThread t2 = new ImplementThread();
t1.setPriority(1);
t1.start();
t2.run();
}
}
Q4. Create an Account class having deposit() & withdraw() methods. Make use of
synchronization while withdrawing money in case of joint account.
import java.io.*;
public class SavingsAccount
{
private double balance;private double interest;
public SavingsAccount()
{
balance = 0;
interest = 0;
}
public SavingsAccount(double initialBalance, double initialInterest)
{
balance = initialBalance;
interest = initialInterest;
}
public void deposit(double amount)
{
balance = balance + amount;
}
public void withdraw(double amount)
{
balance = balance - amount;
}
public void addInterest()
{
balance = balance + balance * interest;
}
public double getBalance()
{
return balance;
}
}