[Android concurrent programming] Three basic methods of Inter-thread communication: android threads
1. Use pipeline stream Pipes
The "Pipeline" is part of the java. io package. It is a feature of Java rather than Android. A "Pipeline" creates a one-way channel for two threads. The producer is responsible for writing data, and the consumer is responsible for reading data.
The following is an example of communication using a pipeline stream.
public class PipeExampleActivity extends Activity { private static final String TAG = "PipeExampleActivity"; private EditText editText; PipedReader r; PipedWriter w; private Thread workerThread; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); r = new PipedReader(); w = new PipedWriter(); try { w.connect(r); } catch (IOException e) { e.printStackTrace(); } setContentView(R.layout.activity_pipe); editText = (EditText) findViewById(R.id.edit_text); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) { } @Override public void onTextChanged(CharSequence charSequence, int start, int before, int count) { try { if(count > before) { w.write(charSequence.subSequence(before, count).toString()); } } catch (IOException e) { e.printStackTrace(); } } @Override public void afterTextChanged(Editable editable) { } }); workerThread = new Thread(new TextHandlerTask(r)); workerThread.start(); } @Override protected void onDestroy() { super.onDestroy(); workerThread.interrupt(); try { r.close(); w.close(); } catch (IOException e) { } } private static class TextHandlerTask implements Runnable { private final PipedReader reader; public TextHandlerTask(PipedReader reader){ this.reader = reader; } @Override public void run() { while(!Thread.currentThread().isInterrupted()){ try { int i; while((i = reader.read()) != -1){ char c = (char) i; Log.d(TAG, "char = " + c); } } catch (IOException e) { e.printStackTrace(); } } } }}
In this example, set a TextWatcher listener for EditText. Once the content of EditText changes, enter a character in the "Pipeline", which is called a producer. At the same time, a working thread reads characters from the pipeline, which is called a consumer. In this way, data communication between the UI thread and the working thread is realized.
2. Shared Memory
Multiple threads share the same memory, that is, a variable can be accessed by multiple threads at the same time. Pay special attention to synchronization and atomic operations.
The most basic synchronization example in Java.
synchronized(this) { while(isConditionFullfilled == false) { wait(); } notify();}If you think it is troublesome to use wait/notify, you can use BlockingQueue provided by Java. From the name, you can see that it is a blocking queue. Let's look at the example below.
public class ConsumerProducer { private final int LIMIT = 10; private BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<Integer>(LIMIT); public void produce() throws InterruptedException { int value = 0; while (true) { blockingQueue.put(value++); } } public void consume() throws InterruptedException { while (true) { int value = blockingQueue.take(); } }}
3. Use Hander and Message
Handler has many tutorials on the Internet. If you are not clear about Handler, You can Google it.
I will give a brief summary.
A thread corresponds to a loose, and a loose holds a MessageQueue. A loose can be bound to multiple Handler, and a MessageQueue can contain multiple messages.
The following is an example of using Handler.
public class HandlerExampleActivity extends Activity { private final static int SHOW_PROGRESS_BAR = 1; private final static int HIDE_PROGRESS_BAR = 0; private BackgroundThread mBackgroundThread; private TextView mText; private Button mButton; private ProgressBar mProgressBar; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_handler_example); mBackgroundThread = new BackgroundThread(); mBackgroundThread.start(); mText = (TextView) findViewById(R.id.text); mProgressBar = (ProgressBar) findViewById(R.id.progress); mButton = (Button) findViewById(R.id.button); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBackgroundThread.doWork(); } }); } @Override protected void onDestroy() { super.onDestroy(); mBackgroundThread.exit(); } private final Handler mUiHandler = new Handler() { public void handleMessage(Message msg) { switch(msg.what) { case SHOW_PROGRESS_BAR: mProgressBar.setVisibility(View.VISIBLE); break; case HIDE_PROGRESS_BAR: mText.setText(String.valueOf(msg.arg1)); mProgressBar.setVisibility(View.INVISIBLE); break; } } }; private class BackgroundThread extends Thread { private Handler mBackgroundHandler; public void run() { Looper.prepare(); mBackgroundHandler = new Handler(); Looper.loop(); } public void doWork() { mBackgroundHandler.post(new Runnable() { @Override public void run() { Message uiMsg = mUiHandler.obtainMessage(SHOW_PROGRESS_BAR, 0, 0, null); mUiHandler.sendMessage(uiMsg); Random r = new Random(); int randomInt = r.nextInt(5000); SystemClock.sleep(randomInt); uiMsg = mUiHandler.obtainMessage(HIDE_PROGRESS_BAR, randomInt, 0, null); mUiHandler.sendMessage(uiMsg); } }); } public void exit() { mBackgroundHandler.getLooper().quit(); } }}
Help android thread communication handler message and so on
Inter-thread communication (three methods )::
Public class AnrActivity extends Activity implements OnClickListener {
TextView text;
Handler handler;
ProgressBar bar;
Private class MyAsycnTask extends AsyncTask <URL, Integer, String> {
@ Override
Protected void onProgressUpdate (Integer... values ){
Bar. setProgress (values [0]);
Text. setText ("Progress:" + values [0] + "% ");
Super. onProgressUpdate (values );
}
@ Override
Protected String doInBackground (URL... params ){
For (int I = 0; I <100; I ++ ){
Try {
PublishProgress (I + 1 );
Thread. sleep (100 );
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
Return "success ";
}
@ Override
Protected void onPostExecute (String result ){
Text. setText (result );
}
}
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
Button down = (Button) this. findViewById (R. id. button1 );
Button Cycler = (Button) this. findViewById (R. id. button2 );
Button update = (Button) this. findViewById (R. id. button3 );
Bar = (ProgressBar) this. findViewById (R. id. progressBar1 );
Text = (TextView) this. findViewById (R. id. text );
Update. setOnClickListener (this );
Down. setOnClickListener (this );
Receiver. setOnClickListener (this );
}
@ Override
Public void onClick (final View v ){
Switch (v. getId ()){
Case R. id. button1:
// Communicate through Asycntask
MyAsycnTask myAsycnTask = new MyAsycnTask ();
MyAsycnT ...... remaining full text>
I was asked how to communicate with two sub-threads in android during the interview.
Construct the mHandlerThread object of the HandlerThread class, so that a subthread can call new MyHandler (mHandlerThread. getloler () to get the handler of the sub-thread. The other sub-thread sends a message, and the sub-thread receives the message instead of the main thread.