您的位置:首页 > 其它

多线程共享互斥“栈”资源

2018-01-11 20:04 267 查看
Client.java

public class Client {

public static void main(String[] args) {
MyStack ms = new MyStack();

PushThread t1 = new PushThread(ms);
PopThread t2 = new PopThread(ms);

        
t1.start();
t2.start();
}
}

MyStack .java

public class MyStack {

private int[] data = new int[30];
private int idx=0;

public void push(int i) {
synchronized (this){
data[idx] = i;
System.out.println("push:"+i);
idx++;
this.notify();//唤醒在wait pool池中的某个线程
}
}

/**
* @param i
*/
public synchronized int pop() {
if(idx<=0){
try {
//CPU资源,两者都会释放的!
//Thread.sleep(10);//sleep不会释放对象锁
this.wait();//wait会释放对象锁,将线程加入wait pool池中
} catch (InterruptedException e) {
e.printStackTrace();
}
}
idx--;
System.out.println("pop:"+ data[idx]);
return data[idx];
}

}

//在段代码中,因为PushThread与PopThread线程的对象都是同一个,所以可以用同一个this对象来锁

//无论是锁方法还是同步块地锁,只要对象锁是同一个,都可以锁成---效果是一样的

PopThread .java

public class PopThread extends Thread{

private MyStack ms=null;
public  PopThread(MyStack ms){
this.ms = ms;

}

@Override
public void run() {
for(int i=20;i>=0;i--){
ms.pop();
}

}

}

PushThread.java

public class PushThread extends Thread{

public MyStack ms = null;
public PushThread(MyStack ms){
    this.ms = ms;
}
public void run() {
for(int i=20;i>=0; i--){
ms.push(i);
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多线程 共享栈