我正在学习使用信号量和多线程的一般情况,但有点卡住了。我有两个线程分别打印G和H,我的目标是交替每个线程的输出,以便输出字符串是这样的;使用信号量从2个线程打印替代输出
G
H
G
H
G
H
每两个类都有类似下面
public class ClassA extends Thread implements Runnable{
Semaphore semaphore = null;
public ClassA(Semaphore semaphore){
this.semaphore = semaphore;
}
public void run() {
while(true)
{
try{
semaphore.acquire();
for(int i=0; i<1000; i++){
System.out.println("F");
}
Thread.currentThread();
Thread.sleep(100);
}catch(Exception e)
{
System.out.println(e.toString());
}
semaphore.release();
}
}
}
下面
的一个布局,我的主类
public static void main(String[] args) throws InterruptedException {
Semaphore semaphore = new Semaphore(1);
ClassA clasA = new ClassA(semaphore);
Thread t1 = new Thread(clasA);
ClassB clasB = new ClassB(semaphore);
Thread t2 = new Thread(clasB);
t1.start();
t2.join();
t2.start();
我得到的输出是太不同我预期结果。任何人都可以帮助我吗?我误用了信号量吗?任何帮助?
如果使用固有锁或重入锁或信号或什么不要紧,只是用锁不执行任何命令 –
OK,请你提出一个前进道路,以获得预期的订单?你会说上面代码的弱点吗? – Jazztheman