Suppose that two masses with different mass are connected by a string in horizontal frictionless table. Then when there is equal acceleration for two masses, string force would extend in some direction. My question here, why don't two boxes create canceling effect for string's stretching? (Often, in we just calculate one box's force opposite to the direction of acceleration and equals to kx, which solves the problem. But why?)
If I understood your question correctly, you are asking why does the spring stretch when it is attached from both sides to two different masses having the same acceleration moving in the same direction.
The reason is that there is a net force exerted on the spring. Newton’s second law states that the force is equal to the mass multiplied by the acceleration. Since the two bodies have different masses and same acceleration, that means one of them is exerting a larger force on spring than the other. This net force causes the string to stretch/compress depending whether the leading mass or the lagging mass has a larger mass.
If you're talking about someone pulling on just one of the blocks, then the spring stretches because it exerts force to pull the other block.
Consider two blocks with masses
m, joined by a spring. Suppose I exert a force
F on mass
M, this will cause it to accelerate, and thus will stretch the spring. As the spring stretches, it exerts a force on the second block (as well as on the first block), causing the second block to accelerate as well.
The spring will keep stretching until the accelerations on the two blocks are equal. At that point one block feels a force
f from the spring, and the other feels a net force
F - f. Since the accelerations are equal, we know
(F - f) / M = f / m, and can use this to calculate the spring force (and how much it stretches, if we know the spring coefficient
If on the other hand you were to put external forces on both blocks so as to give them equal accelerations, then the spring wouldn't need to stretch at all.