借助Lock把MyStack修改为线程安全的类
package P4_14;
import java.util.LinkedList;
import java.util.concurrent.locks.ReentrantLock;
public class MyStack{
private ReentrantLock lock=new ReentrantLock(true);
private LinkedList<Integer> list=new LinkedList<>();
public void push(Integer Num){
try{
lock.lock();
list.addLast(Num);
}finally {
lock.unlock();
}
}
public Integer pop() {
try {
lock.lock();
return list.removeLast();
}finally {
lock.unlock();
}
}
public Integer peek(){
return list.getLast();
}
}
package P4_14;
public class Demo {
public static void main(String[] args) {
MyStack myStack = new MyStack();
for (int i = 0; i < 5; i++) {
int finalI = i;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
myStack.push(finalI * 3);
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 5; i++) {
System.out.println(myStack.pop());
}
}
}