doubt on synchronized block-2
the general form of synchronized block is
Code :
class table
{
......
.
void printTable(int n)
{
synchronized(object)
{
......
}
}
}
--------------------------------------------------------
here object means object of tble class or object of integer or sting... etc classes.
I want a programme which gets lock on object of string class or object of interger class.I mean the above object should be object of string class or object of integer class.
can any one give that programe.?
I request you to give that programme by editing below programme.
------------------------------------------------------------
Code :
import java.io.*;
class table
{
void printTable(int n)
{
synchronized(this)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try{
Thread.sleep(500);
}
catch(InterruptedException ie)
{System.out.println(ie);
}
}
}
}
}
class MyThread1 extends Thread
{
table t;
MyThread1(table t)
{
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread
{
table t;
MyThread2 (table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
class synchronizedblock1
{
public static void main(String args[]
)
{
table t=new table();
MyThread1 t1=new MyThread1(t);
MyThread2 t2=new MyThread2(t);
t1.start();
t2.start();
}
}
==========================
output:
5
10
15
20
25
100
200
300
400
Re: doubt on synchronized block-2
Have you read the tutorial?
Synchronization (The Java™ Tutorials > Essential Classes > Concurrency)
Quote:
I want a programme which gets lock on object of String class
Code :
String aStr = "";
...
synchronized(aStr) {
// have lock on aStr
}
If you want anyone to test your code, you need to properly format it. Statements should not all start in the first column. There should be indentations for nested code.
Re: doubt on synchronized block-2