  In this paper, we study the thermodynamics and phase transition of a BTZ
black hole in a finite space region, namely a cavity. By imposing a
temperature-fixed boundary condition on the wall of the cavity and evaluating
the Euclidean action, we derive the thermodynamic quantities and then construct
the first law of thermodynamics for a static and neutral BTZ black hole, a
rotating BTZ black hole and a charged BTZ black hole, respectively. We prove
that heat capacities of these three types of black holes are always
non-negative. Considering a grand canonical ensemble, we find that the
non-extreme rotating black hole and the charged black hole are locally
thermodynamically stable by calculating the Hessian matrix of their internal
energy. At the phase transition level, it shows that for the static and neutral
BTZ black hole, the phase transition only exists between thermal AdS3 spacetime
and the black hole. The temperature where the phase transition occurs is only
determined by the cavity radius. For rotating and charged cases, there may
exist an extra second-order phase transition between the black hole and the
black hole-cavity merger state. The phase structure of a BTZ black hole in a
cavity shows strong dissimilarities from that without the cavity.
