Lock Contention Program
class Table {
void printTable(int n)
{
for (int i=0; i<10; i++)
{
System.out.println(n*i);
try
{
Thread.sleep(2000);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread {
Table table;
public MyThread1(Table table)
{
this.table = table;
}
@Override
public void run()
{
table.printTable(5);
}
}
class MyThread2 extends Thread {
Table table;
public MyThread2(Table table)
{
this.table = table;
}
@Override
public void run()
{
table.printTable(10);
}
}
public class Test {
public static void main(String[] args) {
Table obj = new Table();
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
}
}
The problem with this code is that both threads are accessing the shared Table
object at the same time, and thus may be interfering with each other's output. One possible solution is to use synchronization to ensure that only one thread can access the printTable
method at a time. Here's an example of how to modify the code to use synchronization
class Table {
synchronized void printTable(int n)
{
for (int i=0; i<10; i++)
{
System.out.println(n*i);
try
{
Thread.sleep(2000);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread {
Table table;
public MyThread1(Table table)
{
this.table = table;
}
@Override
public void run()
{
table.printTable(5);
}
}
class MyThread2 extends Thread {
Table table;
public MyThread2(Table table)
{
this.table = table;
}
@Override
public void run()
{
table.printTable(10);
}
}
public class Test {
public static void main(String[] args) {
Table obj = new Table();
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
}
}
In this modified code, the printTable
method is declared with the synchronized
keyword, which means that only one thread can execute it at a time.
This ensures that the output of the multiplication tables will not be
interleaved or otherwise interfered with.
0 comments:
Post a Comment