There is actually more than 1 question.
Given Model View and Controller. (Mine are coupled a lot – View knows its Controller, and Controller knows View.)
Does new threads in Controller can be fired in basic manner – with the new Runnable(){ (...) run(){}} or it is required to do in some “swing way”, to make it properly? Maybe with Timer or invokeLater()?
Second thing is – assuming that new thread has started – when it operates directly on view, setting some JTextFields (and so on) – do methods such as setThatTextFieldWithNewValue(msg) need to be synchronized as a result of being called from need thread? If so – is there any better approach that gives less coupling and less spend time thinking about needed synchronization?
Anything in swing has to run on the EventQueue. If you have a method called from swing it will already be running there (as in an Action listener). If you don’t know if you’re on the event queue,
EventQueue.isDispatchThread()will tell you. When you know you’re not, reference a swing class or method usingEventQueue.invokeLater()orinvokeAndWaitif you need to see results. (This must be done from themainmethod.)Be very careful about this; you have to check your code. If not, my experience is that the swing UI will be just a little bit flakey, with the occasional unreproducable oddity. There’s no easy way around eyeballing each line of code.
Actually, there is. Do everything on the EventQueue, then you won’t have to worry. You’re probably not doing a whole lot of work outside swing anyway. If you are, it’s probably worth the loss of speed to avoid multithreading problems. If your non-swing work is extensive but simple, use the SwingWorker class. It gives you an extra thread under highly controlled conditions and should save you a lot of grief.
Your classes (View and Controller) are independent of threads, and should work just fine all running in one thread. Don’t confuse classes and threads. (I’ll admit, I’d be tempted to have the Controller firing off threads in all directions, but you have to be prepared to be very careful and know everything there is to know about multithreading.)
If you do multithread, the EventQueue can be a bit handy because you don’t have to protect fields referenced only there–it’s an island of single threading in a dangerous sea. On the other hand, don’t do any synchronization there; you’ll block your UI. You can launch threads from there and you may have to just to avoid blocking. (Once you start multithreading, it’s hard to stop.)