What causes a substance to gain thermal energy?