Similarities and differences between data sharing between Java threads and data sharing between Android threads

Source: Internet
Author: User
Tags message queue thread class

(i) Java multithreaded programming methods for accessing shared objects and data

1, each thread executes the same code, for example, selling tickets: Multiple windows at the same time to sell the 100 tickets, the 100 tickets require multiple threads to share.
2, each thread executes different code, such as: the design of four threads, of which two threads each time to J 1, the other two threads each to J 1 reduction.

A, if each thread executes the same code, you can use the same Runnable object, which has shared data. Selling tickets can do this, each window is doing a sales ticket task, selling tickets are the same data (click to see the specific case). b, if each thread executes different code, you need to use a different runnable object, there are two ways to achieve data sharing between runnable objects:
1. The shared data is encapsulated into an object separately, and the methods of manipulating the shared data are provided in the object, which can facilitate the mutual exclusion and communication of the operation of the shared data.
2, the various runnable objects as the internal class of a class, shared data as a member of the external class variables, the operation of the shared data is also provided in the external class, in order to achieve mutual exclusion and communication, the internal class of the Runnable object calls the external class to manipulate the method of sharing data

Demon:

Package com.ljq.test.thread;

/**
* How data is shared among multiple threads
*
* Design four threads, of which two threads add 1 to J each time, and two threads reduce the J by 1 at a time. Cycle 100 times.
*
* @author Xuhong.tian
*
*/
public class Multithreadsharedatademon {

public static void Main (string[] args) {
Sharedata data2 = new Sharedata ();
New Thread (New Decrementrunnable (DATA2)). Start ();
New Thread (New Incrementrunnable (DATA2)). Start ();

Final Sharedata data1 = new Sharedata ();
New Thread (New Runnable () {
@Override
public void Run () {
Data1.decrement ();

}
). Start ();
New Thread (New Runnable () {
@Override
public void Run () {
Data1.increment ();

}
). Start ();

}

}

/**
* Create a thread class that is responsible for reducing the J by 1
*
* @author Administrator
*
*/
Class Decrementrunnable implements Runnable {
Private sharedata data;

Public decrementrunnable (Sharedata data) {
This.data = data;
}

public void Run () {
for (int i = 0; i < i++) {
Data.decrement ();
}

}
}

/**
* Create a thread class that is responsible for adding 1 to J
*
* @author Administrator
*
*/
Class Incrementrunnable implements Runnable {
Private sharedata data;

Public incrementrunnable (Sharedata data) {
This.data = data;
}

public void Run () {
for (int i = 0; i < i++) {
Data.increment ();
}

}
}

/**
* Encapsulates shared data
*
* @author Administrator
*
*/
Class Sharedata {
private int count = 0;

/**
* Add 1 to J each time
*/
public synchronized void increment () {
count++;
System.out.println ("j++=" + count);
}

/**
* Reduced by 1 per j
*/
Public synchronized void decrement () {
count--;
System.out.println ("j--=" + count);
}

}

(ii) ANDRIOD Communication and data sharing

On Android, the threads here are divided into threads with message loops and threads with no message loops, and threads with message loops typically have a looper, a new Android concept. Our primary thread (UI thread) is the thread of a message loop. In response to this message cycle mechanism, we introduce a new mechanism handler, we have a message loop, we have to send the message loop to the corresponding message, custom messages will generally have their own corresponding processing, message delivery and removal, these are encapsulated in the handler inside, Note that handler is only for those threads that have looper, whether it is a UI thread or a child thread, as long as you have looper, I can add things to your message queue and do the appropriate processing.

But there is one more thing about UI-related things that you can't put in a child thread, because a child thread cannot manipulate the UI, only data, systems, and other non-UI operations.

The creation of a handler is bound to the thread's message queue, and if it was created on the main thread, there is no need to write code to create the message queue, and the default message queue is created in the main thread. However, if you are on a child thread, you must initialize the thread's message queue before creating the handler.


Package Com.bgxt.datatimepickerdemo;
 2 3 Import android.app.Activity;
 4 Import Android.os.Bundle;
 5 Import Android.os.Handler;
 6 Import Android.view.View;
 7 Import Android.widget.Button;
 8 Import Android.widget.TextView; 9 public class HandlerPostActivity1 extends activity {one private Button btnmes1,btnmes2; private TextView
Tvmessage;
13//Declare a Handler object private static Handler handler=new Handler (); @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (Savedinstan
Cestate);        
Setcontentview (r.layout.message_activity);
btnmes1= (Button) Findviewbyid (r.id.btnmes1);
Btnmes2= (Button) Findviewbyid (r.id.btnmes2);
Tvmessage= (TextView) Findviewbyid (r.id.tvmessage);             Btnmes1.setonclicklistener (New View.onclicklistener () {@Override 27 public void OnClick (View v) {28//New START a child thread
New Thread (New Runnable () {@Override 31
public void Run () {+//Tvmessage.settext ("..."); 33//Above error, unable to access UI component in child thread, properties of UI component must be accessed in UI thread 34//UI components are modified using POST method Tvmessag E's Text property handler.post (new Runnable () {@Over Ride Notoginseng public void Run () {Tvmessage.settext ("use Handler.po St sends a section of execution to the message queue in the worker thread and executes in the main thread.                        
");                                
39} 40});
()). Start ();
43} 44});              Btnmes2.setonclicklistener (New View.onclicklistener () {49 @Override public void OnClick (View v) {new ThreaD (New Runnable () {Wuyi @Override public void Run () {53                         Modify the Tvmessage Text property value of the UI component by using the Postdelayed method 54//And delay 3S execution 55                             Handler.postdelayed (New Runnable () {58 @Override public void Run () {Tvmessage.settext ("use handler.postdelayed Sends a paragraph in the thread execution to the message queue, delaying 3S execution in the main thread.    
");                        
60 61} 62}, 3000);
}). Start ();
65 66} 67});

 68} 69}
Package Com.bgxt.datatimepickerdemo;
 2 3 Import Org.apache.http.HttpResponse;
 4 Import org.apache.http.client.HttpClient;
 5 Import Org.apache.http.client.methods.HttpGet;
 6 Import org.apache.http.impl.client.DefaultHttpClient;
 7 Import Org.apache.http.util.EntityUtils;
8 9 Import android.app.Activity;
Import Android.app.ProgressDialog;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.ImageView; public class HandlerPostActivity2 extends activity {private Button btndown; private ImageView Ivimag
E
private static String image_path = "Http://ww4.sinaimg.cn/bmiddle/786013a5jw1e7akotp4bcj20c80i3aao.jpg";
ProgressDialog Private Dialog;
24//A static Handler,handler recommendation is declared as static Handler handler=new Handler (); @Override protected void OnCreate(Bundle savedinstancestate)         {super.oncreate (savedinstancestate); Setcontentview (r.layout.asynctask_activity); 30 31
Btndown = (Button) Findviewbyid (R.id.btndown);
Ivimage = (ImageView) Findviewbyid (r.id.ivsinaimage);
dialog = new ProgressDialog (this);
Dialog.settitle ("hint");
Dialog.setmessage ("Downloading, please later ...");
Panax Notoginseng dialog.setcancelable (false);             Btndown.setonclicklistener (New View.onclicklistener () {@Override 41 public void OnClick (View v) {42//opens a child thread for downloading picture new thread (new Mythread ()).
Start ();
44//Display dialog box Dialog.show ();
46} 47}); The public class Mythread implements Runnable {@Override a public void run () {54//Download a picture of httpclient httpclient = new Defaulthttpclient (); 56            HttpGet httpget = new HttpGet (image_path);
HttpResponse HttpResponse = null; A try {HttpResponse = Httpclient.execute (HttpGet);                             Tstatusline (). Getstatuscode () = () {byte[] data = Entityutils.tobytearray (HttpResponse 62
. GetEntity ()); 63//Get a Bitmap object, and in order to make it accessible within post, must be declared final Bitmap bmp=bitmapfactory.
Decodebytearray (data, 0, data.length);                         Handler.post (New Runnable () {67 @Override                             public void Run () {68//Operating UI component in post ImageView 69
Ivimage.setimagebitmap (BMP);
70} 71});
72//Hide dialog box Dialog.dismiss (); The ' I ' catch (ExCeption e) {e.printstacktrace (); 77} 78} 79 80} 81} 

Http://www.cnblogs.com/jackhuclan/archive/2013/07/10/3182084.html
Http://www.cnblogs.com/allin/archive/2010/05/19/1738800.html
http://blog.csdn.net/lmj623565791/article/details/38377229






Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.