我尝试在Application类中创建一个共享锁,并将其传递给创建线程并使用该锁的方法参数。我希望由一个类的实例创建的线程与由另一个类的实例创建的线程同步。
Alpha 类有一个 start(Object SharedLock),它创建一个新线程。
public void start(Object sharedLock) {
Thread t = new Thread(() -> {
while(true) {
synchronized(sharedLock) {
test();
}
try {
TimeUnit.SECONDS.sleep(db.timeInterval)
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
}
})
}
Alpha类有两个基类Beta和Gama,它们从Application类调用start()方法。下面是代码片段
@Override
public void run(String... args) {
beta.start(sharedLock);
gama.start(sharedLock)
}
test() 在子类中被重写 - beta 和 gama。
这是 test() 的实现
public class Beta extends Aplha {
@Override
public void test() {
Timer timer = new Timer();
final int[] count = {1};
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println(count[0]);
count[0]++;
if (count[0] > 20) {
timer.cancel();
}
}
}
}
}
public class Gama extends Alpha {
@Override
public void test() {
System.out.println("Gama thread")
}
}
一次只能有一个线程能够执行 test()。因此,如果 beta 线程首先调用 start() 那么它应该打印 1 到 20,然后 gama 线程执行 start()
此外,当一个线程渗透时,另一个线程可以通过访问锁来执行
我怎样才能实现这种行为?
尝试信号量:
public static void start(Semaphore sharedLock) {
Thread t = new Thread(() -> {
while (true) {
try {
sharedLock.acquire();
test();
sharedLock.release();
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
t.start();
}
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(1);
start(semaphore);
start(semaphore);
}