synchronized
suggest changeThe synchronized modifier controls access to a method or block by multiple threads. Only one thread at a time can enter a synchronized method or block for a given lock. The synchronized keyword uses an object's intrinsic lock: an instance method uses the current object's lock, and a static method uses the Class object. Any thread trying to execute a synchronized block must acquire the object lock first.
class Shared
{
int i;
synchronized void SharedMethod()
{
Thread t = Thread.currentThread();
for(int i = 0; i <= 1000; i++)
{
System.out.println(t.getName()+" : "+i);
}
}
void SharedMethod2()
{
synchronized (this)
{
System.out.println("This access to the current object is synchronized "+this);
}
}
}
public class ThreadsInJava
{
public static void main(String[] args)
{
final Shared s1 = new Shared();
Thread t1 = new Thread("Thread - 1")
{
@Override
public void run()
{
s1.SharedMethod();
}
};
Thread t2 = new Thread("Thread - 2")
{
@Override
public void run()
{
s1.SharedMethod();
}
};
t1.start();
t2.start();
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents