62,628
社区成员
发帖
与我相关
我的任务
分享
public class TestProducerConsumer {
public static void main(String[] args) throws InterruptedException {
for(int i=0;i<9;i++){
new Push().start();
}
for(int i=0;i<3;i++){
new Pop().start();
}
//睡眠以保证 上面的线程都执行完毕
Thread.sleep(500);
System.out.println(Synch.currentId);
}
}
//调用pop的线程类
class Pop extends Thread{
@Override
public void run() {
try {
new Synch().pop(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//调用push的线程类
class Push extends Thread{
@Override
public void run() {
try {
new Synch().push(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//设计同步的类
class Synch{
public static int currentId = 1;
//负责把currentId --,中间睡眠2毫秒 来测试别的线程是否会干扰
public synchronized void pop(String name) throws InterruptedException{
int temp = currentId;
temp--;
Thread.sleep(2);
System.out.println(name+"--------");
currentId=temp;
}
//负责把currentId ++,中间睡眠6毫秒 来测试别的线程是否会干扰
public synchronized void push(String name) throws InterruptedException{
int temp = currentId;
temp++;
Thread.sleep(6);
System.out.println(name+"+++++++++");
currentId=temp;
}
}
private Synch synch;
public Pop(Synch synch) {
this.synch = synch;
}
[/quote]
非常感谢,我再屡屡思路private Synch synch;
public Pop(Synch synch) {
this.synch = synch;
}
Synch synch=new Synch();
for(int i=0;i<9;i++){
new Push(synch).start();
}
for(int i=0;i<3;i++){
new Pop(synch).start();
}
//睡眠以保证 上面的线程都执行完毕
Thread.sleep(500);
System.out.println(Synch.currentId);