在Java中,将对共享资源的操作放置在lock.lock();和lock.unlock();之间,在本代码,在同一时间内,只有一个线程可以获得锁,
也就是说只有该线程可以对共享资源进行操作,其他线程只能一直等待。
在本例代码中final Business business = new Business(); business 在多个子线程是同一个对象,在多个子线程中针对business的count属性
进行操作,这就是本例中的共享资源了。
package three.day.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockTest {
/**
* @param args
*/
public static void main(String[] args) {
final Business business = new Business();
ExecutorService service = Executors.newFixedThreadPool(3);
for(int i=0;i<1000;i++){
service.execute(new Runnable(){
public void run(){
business.service();
}
});
}
service.shutdown();
}
}
class Business{
private int count = 0;
Lock lock = new ReentrantLock();
public void service(){
lock.lock();
count++;
try {
Thread.sleep(1000);
System.out.println(count);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
}
输出结果:
1
2
3
4
5
6
7
8
9
.......
这样就能保证多个线程有序的输出1,2,3,4,5......