★带互斥的共享栈
多线程互斥共享“栈”资源
public class myStack {
//共享栈:先进后出
int idx=0;
char[] c=new char[9];
void put(char ch){
//同步块:对象锁是指定的
synchronized (this) {
c[idx++] = ch;
System.out.println("push:"+ch);
this.notify();
}
}
//同步方法:对象锁是该方法的拥有者--静态方法是类,非静态是this对象
public synchronized char pop(){
if(idx<1){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
char ch=c[--idx];
System.out.println("---pop:"+ch);
return ch;
}
}
public class pushThread extends Thread {
myStack ms=null;
public pushThread(myStack ms){
this.ms=ms;
}
@Override
public void run() {
for(int i=97;i<103;i++){
ms.put((char)i);
}
}
}
public class popThread extends Thread {
myStack ms=null;
public popThread(myStack ms){
this.ms=ms;
}
@Override
public void run() {
for(int i=1;i<10;i++){
ms.pop();
}
}
}
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();
}
}