我正在學習使用信號量和多線程的一般情況,但有點卡住了。我有兩個線程分別打印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