我试图实现锁定解锁同步。下面的代码有两个线程试图同时访问一个字段,这个代码我可以实现synchronized关键字使它同步,但我想特别实现Lock - 解锁属于ReentrantLock类。
第一个线程是10000,第二个线程是10000.一旦同步,输出必须是20000。
要实现Lock-Unlock,我尝试了以下代码:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class App
{
int count = 0;
public static void main (String[] args)
{
App a = new App();
a.doWork();
}
public Lock sync = new ReentrantLock();
public void synchronize() //Here i created a method to try to make work the access one by one
{
sync.lock();
try
{
count++;
}
finally
{
sync.unlock();
}
}
public void doWork()
{
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
for (int i = 0; i < 10000; i++)
{
synchronize();
}
}
});
Thread t2 = new Thread(new Runnable()
{
public void run()
{
for (int i =0; i <10000; i++)
{
synchronize();
}
}
});
t1.start();
t2.start();
System.out.println("count is " + count);
}
}
如何实现Lock - 从ReentrantLock类解锁,没有其他方法。