10. Çoklu Thread Modeli Mümkün mü?
From Brian Goetz's
"Java Concurrency in Practice" Book
9.1 Why are GUIs single-threaded?
Single-threaded GUI frameworks are not unique to Java; Qt, NextStep,
MacOS Cocoa, X Windows, and many others are also single-threaded. This
is not for lack of trying; there have been many attempts to write
multithreaded GUI frameworks, but because of persistent problems with
race conditions and deadlock...
UI Thread UI ThreadUI ThreadUI Thread
UI Thread
14. Problem 2
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
...
btnSave.setImageResource(R.drawable.progress1);
...
}
}).start();
}
15. Problem 2
android.view.ViewRootImpl$CalledFromWrongThreadException:
Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4746)
...
at android.widget.ImageView.setImageResource(ImageView.java:352)
at mca.activities.NoteListActivity$3$1.run(NoteListActivity.java:69)
at java.lang.Thread.run(Thread.java:856)
16. Thread Safe
Brian Goetz "Java Concurrency in Practice"
"A class is thread-safe if it behaves correctly when accessed
from multiple threads, regardless of the scheduling or
interleaving of the execution of those threads by the
runtime environment, and with no additional
synchronization or other coordination on the part of the
calling code."
18. runOnUiThread vs. post
● küçük farklılık?
● Şu anki thread UI thread'i ise Runnable çalıştırılır
değilse mesaj kuyruğuna eklenir.
● Runnable'ın UI Thread'inin mesaj kuyruğuna
eklenmesini sağlar.
19. Solution 2.1
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
NoteListActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
btnTest.setImageResource(R.drawable.progress1);
}
});
}
}).start();
}
20. Solution 2.2
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
btnTest.post(new Runnable() {
@Override
public void run() {
btnTest.setImageResource(R.drawable.progress1);
}
});
}
}).start();
}