Always want to use Java to implement the stack, queue, but no time, immediately to find an internship, on the review of the algorithm, to achieve a simple stack, the code is still problematic, interested brothers help correct
Problem: Multi-threaded words pop and push can only have one method to be executed need to add mutex variable
Importjava.util.Arrays; Public classStack<item> { Private transientobject[] data;//Storing Data Private intTop//represents the top element of the stack Private intoldcapacity; PublicStack () {oldcapacity= 100; Data=NewObject[oldcapacity];//need to expand to re-build the array, copy this to the pasttop =-1; } Public synchronized voidPut (Item t) {//Press Stack if(Top >oldcapacity-2) { intNewcapacity = (oldcapacity * 3)/2 + 1;//imitate ArrayList to increase the length of array lengthOldcapacity =newcapacity; Data=arrays.copyof (data, newcapacity); } Top++; Data[top]=T; } Public synchronizedItem Pop () {//out of the stack if(Top < 0) { return NULL; } Item T=(Item) data[top]; Top--; returnT; }}
Java implementation stack (can be put in infinity)