synchronized(this)与synchronized(class) 简单实例

简介:

参考:http://www.cnblogs.com/highriver/archive/2011/12/18/2291965.html


通过对以上文章的拜读,我进一步加深了对线程同步锁的理解。

下面就根据自己的理解,进行的简单实例操作演示。

在看下面的代码前,强烈建议先拜读上面的文章。

源码下载:http://download.csdn.net/detail/yang_hui1986527/4423728


MainActivity.java

package com.snowdream.demo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {

	private static final int MSG_CLEAR = 0;
	private static final int MSG_UPDATE = 1;

	private final Object mObject = new Object();
	private final String tag = "MainActivity";
	ExecutorService pool = null; 

	private static TextView mTextView = null;

	private static Handler mHandler = new Handler(){
		public void handleMessage(Message msg){
			switch (msg.what) {
			case MSG_CLEAR:
				mTextView.setText("");
				break;
			case MSG_UPDATE:
				String str = (String)msg.obj;
				if (!TextUtils.isEmpty(str)) {
					mTextView.append(str);
					mTextView.append("\n");
				}
				break;
			default:
				break;
			}
		};
	};


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
		initData();
	}


	private void initView() {
		mTextView = (TextView)findViewById(R.id.textView1);
	}

	private void initData() {
		pool = Executors.newFixedThreadPool(2); 
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
		pool.shutdown();
	}

	public void OnButton1Click(View view) {
		int id = view.getId();
		switch (id) {
		case R.id.button1:
			//synchronized(class)
			//synchronized(this)
			mHandler.sendMessage(mHandler.obtainMessage(MSG_CLEAR));
			
			Sync1_Class sync1_Class = new Sync1_Class();
			Sync1_Object sync1_Object = new Sync1_Object();
			pool.execute(sync1_Class);
			pool.execute(sync1_Object);
			break;
		case R.id.button2:
			//synchronized(this)
			//synchronized(this)
			mHandler.sendMessage(mHandler.obtainMessage(MSG_CLEAR));
			
			Sync2_Object_1  sync2_Object_1 = new Sync2_Object_1();
			Sync2_Object_2 sync2_Object_2 = new Sync2_Object_2();
			pool.execute(sync2_Object_1);
			pool.execute(sync2_Object_2);	
			break;
		case R.id.button3:
			//synchronized(class)
			//synchronized(class)
			mHandler.sendMessage(mHandler.obtainMessage(MSG_CLEAR));

			Sync3_Class_1 sync3_Class_1 = new Sync3_Class_1();
			Sync3_Class_2 sync3_Class_2 = new Sync3_Class_2();
			pool.execute(sync3_Class_1);
			pool.execute(sync3_Class_2);
			break;
		default:
			break;
		}
	}

	public class Sync1_Class implements Runnable {
		public void run() {
			synchronized(MainActivity.class){
				for (int i = 0; i < 100; i++) {
					Log.i(tag, "Sync1_Class: "+ i);
					
					mHandler.sendMessage(mHandler.obtainMessage(MSG_UPDATE, "Sync1_Class: "+ i));
				}
			}	
		}
	} 


	public class Sync1_Object implements Runnable {
		public void run() {
			synchronized(mObject){
				for (int i = 0; i < 100; i++) {
					Log.i(tag, "Sync1_Object: "+ i);
					
					mHandler.sendMessage(mHandler.obtainMessage(MSG_UPDATE,  "Sync1_Object: "+ i));
				}
			}
		}
	} 



	public class Sync2_Object_1 implements Runnable {
		public void run() {
			synchronized(mObject){
				for (int i = 0; i < 100; i++) {
					Log.i(tag, "Sync2_Object_1: "+ i);
					
					mHandler.sendMessage(mHandler.obtainMessage(MSG_UPDATE,  "Sync2_Object_1: "+ i));
				}
			}
		}
	} 


	public class Sync2_Object_2 implements Runnable {
		public void run() {
			synchronized(mObject){
				for (int i = 0; i < 100; i++) {
					Log.i(tag, "Sync2_Object_2: "+ i);
					
					mHandler.sendMessage(mHandler.obtainMessage(MSG_UPDATE,  "Sync2_Object_2: "+ i));
				}
			}
		}
	} 


	public class Sync3_Class_1 implements Runnable {
		public void run() {
			synchronized(MainActivity.class){
				for (int i = 0; i < 100; i++) {
					Log.i(tag, "Sync3_Class_1: "+ i);
					
					mHandler.sendMessage(mHandler.obtainMessage(MSG_UPDATE,  "Sync3_Class_1: "+ i));
				}
			}
		}
	} 


	public class Sync3_Class_2 implements Runnable {
		public void run() {
			synchronized(MainActivity.class){
				for (int i = 0; i < 100; i++) {
					Log.i(tag, "Sync3_Class_2: "+ i);
					
					mHandler.sendMessage(mHandler.obtainMessage(MSG_UPDATE,  "Sync3_Class_2: "+ i));
				}
			}
		}
	} 

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
}



activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true" >

        <Button
            android:id="@+id/button1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:onClick="OnButton1Click"
            android:text="Button1" />

        <Button
            android:id="@+id/button2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:onClick="OnButton1Click"
            android:text="Button2" />

        <Button
            android:id="@+id/button3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:onClick="OnButton1Click"
            android:text="Button3" />
    </LinearLayout>

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/linearLayout1"
        android:layout_toLeftOf="@+id/textView1" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="@dimen/padding_small"
            android:text="Loading..."
            tools:context=".MainActivity" />
    </ScrollView>

</RelativeLayout>

效果预览:


相关文章
|
7月前
|
Java
9.synchronized 是个啥东西?应该怎么使用?
9.synchronized 是个啥东西?应该怎么使用?
60 0
9.synchronized 是个啥东西?应该怎么使用?
synchronized(this)、synchronized(class)和synchronized(Object)的区别
synchronized(this)、synchronized(class)和synchronized(Object)的区别
133 0
synchronized(this)、synchronized(class)和synchronized(Object)的区别
|
程序员 调度
多线程之Thread 类的基本用法
多线程之Thread 类的基本用法
|
前端开发 Java Spring
方法上加上 synchronized 就可以了么
方法上加上 synchronized 就可以了么
|
存储 消息中间件 缓存
Android高级:内部类的理解,多态,run和start,wait和seelp,线程安全,堆和栈,synchronized 和volatile ,AsyncT
Android高级:内部类的理解,多态,run和start,wait和seelp,线程安全,堆和栈,synchronized 和volatile ,AsyncT
161 0
|
Java
JAVA同步锁 synchronized(this)、synchronized(class)与synchronized(Object)的区别
利用实例介绍JAVA同步锁 synchronized(this)、synchronized(class)与synchronized(Object)的区别
146 0
JAVA同步锁 synchronized(this)、synchronized(class)与synchronized(Object)的区别
|
安全 Java Spring
Synchronized代码详解?
Synchronized代码详解?
synchronized(this)、synchronized(.class)、锁静态方法、方法区别?
synchronized(this)、synchronized(.class)、锁静态方法、方法区别?
synchronized 加锁 this 和 class 的区别!(3)
synchronized 加锁 this 和 class 的区别!(3)
121 0
synchronized 加锁 this 和 class 的区别!(3)
synchronized 加锁 this 和 class 的区别!(5)
synchronized 加锁 this 和 class 的区别!(5)
126 0
synchronized 加锁 this 和 class 的区别!(5)