I have a Mega with 40 LEDs attached pins 2-42
Do you have a current limit resistor on each LED?
At 20 mA/LED, 40 LEDs on at once could exceed the total current limit of the Mega, and the Mega voltage regulator will probably overheat.
https://playground.arduino.cc/Main/ArduinoPinCurrentLimitations