Multithreaded working but with some strange behaviour