我正在尝试写一个使用线程的基本程序。假设我有两个线程,t1和t2,以及锁x。假设锁x被分配给t1。什么时候会出现由于锁x被分配给t1而导致t2无法处理的情况?我正在尝试创建一个简单的示例来演示锁/线程是如何工作的。
我很感谢在这件事上的任何帮助。
这就是我到目前为止得到的:
天行者类:
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Skywalker{
public static void main(String args[]){
Thread t1 = new Thread("station 1");
Thread t2 = new Thread("station 2");
t1.start();
t2.start();
}
}Darth类:
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Darth implements Runnable{
String stationName;
Lock x = new ReentrantLock();
Random r = new Random();
public Darth(String name){
stationName = name;
}
public void run(){
try{
x.lock();
System.out.println(stationName + "is working");
sleep(randomTime);
x.unlock();
} catch(Exception e) {
}
}
}发布于 2012-09-18 05:41:04
您应该将锁放在一个单独的类中,以保护“资源访问”,例如:
class SharedResource {
private static Lock lock = new ReentrantLock();
public static void consumeResource(){
try{
lock.lock();
//just one thread a time here
int i = 10;
//mock consuming shared resource:
while(i>0){
i--;
System.out.println(Thread.currentThread().getName() + " is in");
Thread.sleep(1000);
}
}finally{
lock.unlock();
}
}
}现在,每次只有一个线程能够访问consumeResource方法中位于lock/unlock语句中的代码行。很容易展示从Darth run方法调用consumeResource。
https://stackoverflow.com/questions/12463427
复制相似问题