题目描述:
目前有三个线程t1,t2,t3,,线程分别打印1,2,3,,让我们如何控制线程的同步访问,使得线程依次输出123123123123…的结果。
解题思路:
使用最简便最实用的信号量Semaphore,通过控制信号的获取以及释放,承接获取锁来实现线程得顺序执行以及临界资源的同步访问。
代码如下:
package 比较器java特性
;
import java
.util
.concurrent
.Semaphore
;
public class SemaphoreT123 {
public static void main(String
[] args
) {
Print123Semaphore ps
= new Print123Semaphore();
new Thread(()->ps
.Print1()).start();
new Thread(()->ps
.Print2()).start();
new Thread(()->ps
.Print3()).start();
}
}
class Print123Semaphore{
private Semaphore s1
=new Semaphore(1);
private Semaphore s2
=new Semaphore(0);
private Semaphore s3
=new Semaphore(0);
public void Print1()
{
print("1",s1
,s2
);
}
public void Print2() {
print("2",s2
,s3
);
}
public void Print3() {
print("3",s3
,s1
);
}
public void print(String name
,Semaphore start
,Semaphore end
)
{
for(int i
=0;i
<10;i
++) {
try {
start
.acquire();
System
.out
.print(name
);
end
.release();
} catch (InterruptedException e
) {
e
.printStackTrace();
}
}
}
}
喜欢的记得点赞关注我哦!