I am very disappointed in Java for not allowing the following code to move as concurrently as it could. When there is no synchronization, the two threads switch more often, but when attempting to access a synchronized method, it will take way too long (like 30 seconds) before the second thread gets the lock, and again before the first thread gets the lock from the second. What coding can take care of sharing the lock better:
public synchronized static void i()
{
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] f)
{
Thread t = new Thread(new Runnable(){
public void run()
{
while(true)
i();
}});
t.setName("a: ");
Thread t2 = new Thread(new Runnable(){
public void run()
{
while(true)
i();
}});
t2.setName("b: ");
t.start();
t2.start();
}
Use
ReentrantLockwith fairness set true.