정적 개념을 사용하지 않으려면 매개 변수에서 아무 것도 전달하지 않아야합니다. 아래 코드에서 두 클래스를 구현했습니다. 여러분이 물어 보았 듯이 두 스레드 클래스에서 공통 핸들러를 사용했습니다. 처리기 h1을 Runnable 객체의 매개 변수로 전달하고 start() 메서드를 사용하여 다른 스레드 클래스의 run() 메서드를 트리거합니다. run() 메서드가 포함 된 스레드는 UI (Main) 스레드입니다. UI를 업데이트하려면 UI 스레드를 사용해야합니다. Worker (Background) 스레드는 UI 업데이트를 수행 할 수 없습니다. 작업자와 UI 간의 통신은 처리기를 통해 수행됩니다. 그래서 UI 스레드 클래스에서 핸들러 h2를 정의합니다. 배경 스레드 클래스에서 UI 스레드 클래스 생성자가 호출되면 생성자에서 가져온 h1에서 h2 값을 가져옵니다. 그리고 저는 의사 소통을 위해 h2를 사용합니다. 사실, h2와 h1은 시스템의 동일한 메모리 공간에 속합니다.
아래 두 클래스를 만들고 참조 용으로 스레드 통신을했습니다.
일등
public class MainActivity extends AppCompatActivity {
Handler h1;
Thread t;
EditText editText;
private Bundle bb = new Bundle();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
h1 = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
bb = msg.getData();
String str = bb.getString("udd");
editText.setText(str);
System.out.println(str);
}
};
t = new Thread(new MyRunnable(h1)); //I pass Runnable object in thread so that the code inside the run() method
//of Runnable object gets executed when I start my thread here. But the code executes in new thread
t.start(); //thread started
try {
t.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
2 등석
public class MyRunnable implements Runnable {
private Handler h2;
public MyRunnable(Handler h) {
this.h2 = h;
}
@Override
public void run() {
//everything inside rum method executes in new thread
for(int i=0;i<10;i++) {
Message m = Message.obtain(); //get null message
Bundle b = new Bundle();
b.putString("udd", "daju");
m.setData(b);
//use the handler to send message
h2.sendMessage(m);
}
}
}
주 : thread.start()가 발생하면, 그것은 실행 가능한 클래스의 실행을 트리거, 그것은 별도의 스레드를 생성한다. 따라서 매번 start()를 호출하면 호출 수신자 스레드의 우선 순위가 동일한 새 스레드가 있습니다.
희망, 도움이되었습니다.
감사합니다. 그것은 나를 위해 일했습니다. – Gokul
나는 기쁜 남자 @ gd16이다. –