Reactor这个词译成汉语还真没有什么合适的,很多地方叫反应器模式,但更多好像就直接叫reactor模式了,其实我觉着叫应答者模式更好理解一些。通过了解,这个模式更像一个侍卫,一直在等待你的召唤,或者叫召唤兽。
并发系统常使用reactor模式,代替常用的多线程的处理方式,节省系统的资源,提高系统的吞吐量。
先用比较直观的方式来介绍一下这种方式的优点,通过和常用的多线程方式比较一下,可能更好理解。
以一个餐饮为例,每一个人来就餐就是一个事件,他会先看一下菜单,然后点餐。就像一个网站会有很多的请求,要求服务器做一些事情。处理这些就餐事件的就需要我们的服务人员了。
在多线程处理的方式会是这样的:
一个人来就餐,一个服务员去服务,然后客人会看菜单,点菜。 服务员将菜单给后厨。
二个人来就餐,二个服务员去服务……
五个人来就餐,五个服务员去服务……
这个就是多线程的处理方式,一个事件到来,就会有一个线程服务。很显然这种方式在人少的情况下会有很好的用户体验,每个客人都感觉自己是VIP,专人服务的。如果餐厅一直这样同一时间最多来5个客人,这家餐厅是可以很好的服务下去的。
来了一个好消息,因为这家店的服务好,吃饭的人多了起来。同一时间会来10个客人,老板很开心,但是只有5个服务员,这样就不能一对一服务了,有些客人就要没有人管了。老板就又请了5个服务员,现在好了,又能每个人都受VIP待遇了。
越来越多的人对这家餐厅满意,客源又多了,同时来吃饭的人到了20人,老板高兴不起来了,再请服务员吧,占地方不说,还要开工钱,再请人就攒不到钱了。怎么办呢?老板想了想,10个服务员对付20个客人也是能对付过来的,服务员勤快点就好了,伺候完一个客人马上伺候另外一个,还是来得及的。综合考虑了一下,老板决定就使用10个服务人员的线程池啦~~~
但是这样有一个比较严重的缺点就是,如果正在接受服务员服务的客人点菜很慢,其他的客人可能就要等好长时间了。有些火爆脾气的客人可能就等不了走人了。
Reactor如何处理这个问题呢:
老板后来发现,客人点菜比较慢,大部服务员都在等着客人点菜,其实干的活不是太多。老板能当老板当然有点不一样的地方,终于发现了一个新的方法,那就是:当客人点菜的时候,服务员就可以去招呼其他客人了,等客人点好了菜,直接招呼一声“服务员”,马上就有个服务员过去服务。嘿嘿,然后在老板有了这个新的方法之后,就进行了一次裁员,只留了一个服务员!这就是用单个线程来做多线程的事。
实际的餐馆都是用的Reactor模式在服务。一些设计的模型其实都是从生活中来的。
Reactor模式主要是提高系统的吞吐量,在有限的资源下处理更多的事情。
在单核的机上,多线程并不能提高系统的性能,除非在有一些阻塞的情况发生。否则线程切换的开销会使处理的速度变慢。就像你一个人做两件事情,1、削一个苹果。2、切一个西瓜。那你可以一件一件的做,我想你也会一件一件的做。如果这个时候你使用多线程,一会儿削苹果,一会切西瓜,可以相像究竟是哪个速度快。这也就是说为什么在单核机上多线程来处理可能会更慢。
但当有阻碍操作发生时,多线程的优势才会显示出来,现在你有另外两件事情去做,1、削一个苹果。2、烧一壶开水。我想没有人会去做完一件再做另一件,你肯定会一边烧水,一边就把苹果削了。
Source: http://daimojingdeyu.iteye.com/blog/828696
转载博客,相当感谢博主
点击进入内容
package com.xiaxing.slidingdrawer; import java.util.ArrayList; import android.content.Context; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.SurfaceView; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ListView; import android.widget.TextView; import com.xiaxing.slidingdrawer.R; public class LeftListView implements View.OnClickListener { public static final int DIRECTION_LEFT = 0; public static final int DIRECTION_RIGHT = 1; public static final int DIRECTION_UP = 2; public static final int DIRECTION_DOWN = 3; private static final String TAG = "xiaxing"; private Context mContext; private final LayoutInflater mInflater; private ListView mAchivementList; private ListView mFriendList; private AchivementAdapter mAchivementAdapter; private FriendAdapter mFriendAdapter; private boolean mIsVisible = true; private Button mAchivementBtn; private Button mFriendBtn; private boolean mIsFriendListVisable = false; private FrameLayout mContainer; public interface OnVisibilityChangedListener { public void onVisibilityChanged(boolean visbility); } public LeftListView(Context context, FrameLayout rootView) { mContext = context; mInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mContainer = rootView; if (this.mContainer == null) Log.e("xiaxing", "mContainer is null"); mInflater.inflate(R.layout.anyclock_layout_achivement_list, mContainer); mFriendList = (ListView)(mContainer.findViewById(R.id.friend_view)); mAchivementList = (ListView)(mContainer.findViewById(R.id.achivement_view)); mAchivementBtn = (Button)(mContainer.findViewById(R.id.btn_achivement)); mAchivementBtn.setOnClickListener(this); mFriendBtn = (Button)(mContainer.findViewById(R.id.btn_friend)); mFriendBtn.setOnClickListener(this); } public boolean isVisible() { return mIsVisible; } public void testPreference() { ArrayList<String> list = new ArrayList<String>(); for (int i = 0, n = 10; i < n; ++i) { list.add("item"); } mFriendAdapter = new FriendAdapter(mContext, list); mFriendList.setAdapter(mFriendAdapter); mFriendList.setOnItemClickListener(mFriendAdapter); mAchivementAdapter = new AchivementAdapter(mContext, list); mAchivementList.setAdapter(mAchivementAdapter); mAchivementList.setOnItemClickListener(mAchivementAdapter); } public void processTouchEvent(MotionEvent event) { Log.v(TAG, "LeftListView onTouch"); // mContainer.onTouchEvent(event); this.mContainer.dispatchTouchEvent(event); } private class FriendAdapter extends BaseAdapter implements OnItemClickListener { private final ArrayList<String> mPreferences; public FriendAdapter(Context context, ArrayList<String> preferences) { mPreferences = preferences; } public void onItemClick( AdapterView<?> parent, View view, int position, long id) { // Preference preference = mPreferences.get(position); // TODO:: Log.v(TAG, "MainMenuAdapter -- " + "onItemClick : " + position); } public View getView(int position, View convertView, ViewGroup parent) { convertView = inflateIfNeed(convertView, R.layout.anyclock_content_achivement_item, parent, false); TextView musictime = (TextView)convertView.findViewById(R.id.grid_music_time); musictime.setText("20120000"); TextView musicname = (TextView)convertView.findViewById(R.id.grid_music_name); musicname.setText("好友名称"); TextView artist = (TextView)convertView.findViewById(R.id.grid_music_artist); artist.setText("你是我的好友吗"); return convertView; } @Override public boolean areAllItemsEnabled() { return false; } // @Override // public boolean isEnabled(int position) { // Preference preference = mPreferences.get(position); // return !(preference instanceof PreferenceGroup); // } public int getCount() { return mPreferences.size(); } public Object getItem(int position) { return null; } public long getItemId(int position) { return position; } // @Override // public int getItemViewType(int position) { // Preference pref = mPreferences.get(position); // if (pref instanceof PreferenceGroup) // return 0; // if (pref instanceof ListPreference) // return 1; // throw new IllegalStateException(); // } @Override public int getViewTypeCount() { // we have two types, see getItemViewType() return 2; } @Override public boolean hasStableIds() { return true; } @Override public boolean isEmpty() { return mPreferences.isEmpty(); } } private class AchivementAdapter extends BaseAdapter implements OnItemClickListener { private final ArrayList<String> mPreferences; public AchivementAdapter(Context context, ArrayList<String> preferences) { mPreferences = preferences; } public void onItemClick( AdapterView<?> parent, View view, int position, long id) { // Preference preference = mPreferences.get(position); // TODO:: Log.v(TAG, "MainMenuAdapter -- " + "onItemClick : " + position); } public View getView(int position, View convertView, ViewGroup parent) { convertView = inflateIfNeed(convertView, R.layout.anyclock_content_achivement_item, parent, false); TextView musictime = (TextView)convertView.findViewById(R.id.grid_music_time); musictime.setText("20120000"); TextView musicname = (TextView)convertView.findViewById(R.id.grid_music_name); musicname.setText("成就名称"); TextView artist = (TextView)convertView.findViewById(R.id.grid_music_artist); artist.setText("成就说明:早起的鸟儿啊???"); return convertView; } @Override public boolean areAllItemsEnabled() { return false; } // @Override // public boolean isEnabled(int position) { // Preference preference = mPreferences.get(position); // return !(preference instanceof PreferenceGroup); // } public int getCount() { return mPreferences.size(); } public Object getItem(int position) { return null; } public long getItemId(int position) { return position; } // @Override // public int getItemViewType(int position) { // Preference pref = mPreferences.get(position); // if (pref instanceof PreferenceGroup) // return 0; // if (pref instanceof ListPreference) // return 1; // throw new IllegalStateException(); // } @Override public int getViewTypeCount() { // we have two types, see getItemViewType() return 2; } @Override public boolean hasStableIds() { return true; } @Override public boolean isEmpty() { return mPreferences.isEmpty(); } } private View inflateIfNeed( View view, int resource, ViewGroup root, boolean attachToRoot) { if (view != null) return view; return mInflater.inflate(resource, root, attachToRoot); } public static Animation slideOut(View view, int to) { view.setVisibility(View.INVISIBLE); Animation anim; switch (to) { case DIRECTION_LEFT: anim = new TranslateAnimation(0, -view.getWidth() + 20, 0, 0); break; case DIRECTION_RIGHT: anim = new TranslateAnimation(0, view.getWidth(), 0, 0); break; case DIRECTION_UP: anim = new TranslateAnimation(0, 0, 0, -view.getHeight()); break; case DIRECTION_DOWN: anim = new TranslateAnimation(0, 0, 0, view.getHeight()); break; default: throw new IllegalArgumentException(Integer.toString(to)); } anim.setDuration(500); view.startAnimation(anim); return anim; } public static Animation slideIn(View view, int from) { view.setVisibility(View.VISIBLE); Animation anim; switch (from) { case DIRECTION_LEFT: anim = new TranslateAnimation(-view.getWidth(), 0, 0, 0); break; case DIRECTION_RIGHT: anim = new TranslateAnimation(view.getWidth(), 0, 0, 0); break; case DIRECTION_UP: anim = new TranslateAnimation(0, 0, -view.getHeight(), 0); break; case DIRECTION_DOWN: anim = new TranslateAnimation(0, 0, view.getHeight(), 0); break; default: throw new IllegalArgumentException(Integer.toString(from)); } anim.setDuration(500); view.startAnimation(anim); return anim; } @Override public void onClick(View v) { // TODO Auto-generated method stub if (v.equals(mFriendBtn)) { Log.v(TAG, "mAchivementBtn clicked"); slideIn(mFriendList, DIRECTION_RIGHT); mIsFriendListVisable = true; } else if (v.equals(mAchivementBtn)) { if (mIsFriendListVisable) { slideOut(mFriendList, DIRECTION_RIGHT); mIsFriendListVisable = false; } Log.v(TAG, "mFriendBtn clicked"); } } }
package com.xiaxing.slidingdrawer; import com.xiaxing.slidingdrawer.R; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.view.GestureDetector; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.FrameLayout; import android.widget.ImageView; public class MainActivity extends Activity implements OnClickListener, OnTouchListener { private LeftListView mAchivementList; private ImageView mGripBtn; private View mListView; private boolean mIsListViewVisale = false; private GestureDetector mGestureDetector; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); findViewById(R.id.viewtag).setOnTouchListener(this); } @SuppressWarnings("deprecation") @Override public void onStart() { super.onStart(); showAchivementList(); mGestureDetector = new GestureDetector(new MyGestureListener()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } public void showAchivementList() { if (mAchivementList == null) { FrameLayout fl = (FrameLayout)findViewById(R.id.mainview); mAchivementList = new LeftListView(this, fl); mAchivementList.testPreference(); } } @Override public void onClick(View view) { // TODO Auto-generated method stub if (view.getId() == mGripBtn.getId()) { Log.v("xiaxing", "main activity onClick"); if (mIsListViewVisale) { LeftListView.slideIn(mListView, LeftListView.DIRECTION_LEFT); mIsListViewVisale = false; } else { LeftListView.slideOut(mListView, LeftListView.DIRECTION_LEFT); mIsListViewVisale = true; } } } @Override public boolean onTouch(View v, MotionEvent event) { mAchivementList.processTouchEvent(event); return mGestureDetector.onTouchEvent(event); } private int verticalMinDistance = 120; private int minVelocity = 0; private class MyGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onDown(MotionEvent arg0) { // TODO Auto-generated method stub // Log.v("xiaxing", "onDown 1"); // if (mIsListViewVisale) // return true; // else // return false; return true; } public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Log.v("xiaxing", "onFling"); if (e1.getX() - e2.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity) { Log.v("xiaxing", "onFling 2"); if (!mIsListViewVisale) { LeftListView.slideOut(mListView, LeftListView.DIRECTION_LEFT); mIsListViewVisale = false; } } else if (e2.getX() - e1.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity) { Log.v("xiaxing", "onFling 1"); if (mIsListViewVisale) { LeftListView.slideIn(mListView, LeftListView.DIRECTION_LEFT); mIsListViewVisale = false; } } return true; } @Override public void onLongPress(MotionEvent arg0) { // TODO Auto-generated method stub Log.v("xiaxing", "onLongPress 2"); } @Override public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) { // TODO Auto-generated method stub Log.v("xiaxing", "onScroll 1"); return true; } @Override public void onShowPress(MotionEvent arg0) { // TODO Auto-generated method stub Log.v("xiaxing", "onShowPress 2"); } @Override public boolean onSingleTapUp(MotionEvent arg0) { // TODO Auto-generated method stub Log.v("xiaxing", "onSingleTapUp 2"); return true; } } }
package com.xiaxing.slidingdrawer; import android.view.View; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; public class Util { private static final String TAG = "Util"; public static final int DIRECTION_LEFT = 0; public static final int DIRECTION_RIGHT = 1; public static final int DIRECTION_UP = 2; public static final int DIRECTION_DOWN = 3; public static Animation slideOut(View view, int to) { view.setVisibility(View.INVISIBLE); Animation anim; switch (to) { case DIRECTION_LEFT: anim = new TranslateAnimation(0, -view.getWidth(), 0, 0); break; case DIRECTION_RIGHT: anim = new TranslateAnimation(0, view.getWidth(), 0, 0); break; case DIRECTION_UP: anim = new TranslateAnimation(0, 0, 0, -view.getHeight()); break; case DIRECTION_DOWN: anim = new TranslateAnimation(0, 0, 0, view.getHeight()); break; default: throw new IllegalArgumentException(Integer.toString(to)); } anim.setDuration(500); view.startAnimation(anim); return anim; } public static Animation slideIn(View view, int from) { view.setVisibility(View.VISIBLE); Animation anim; switch (from) { case DIRECTION_LEFT: anim = new TranslateAnimation(-view.getWidth(), 0, 0, 0); break; case DIRECTION_RIGHT: anim = new TranslateAnimation(view.getWidth(), 0, 0, 0); break; case DIRECTION_UP: anim = new TranslateAnimation(0, 0, -view.getHeight(), 0); break; case DIRECTION_DOWN: anim = new TranslateAnimation(0, 0, view.getHeight(), 0); break; default: throw new IllegalArgumentException(Integer.toString(from)); } anim.setDuration(500); view.startAnimation(anim); return anim; } public static boolean equals(Object a, Object b) { return (a == b) || (a == null ? false : a.equals(b)); } public static <T> T checkNotNull(T object) { if (object == null) throw new NullPointerException(); return object; } }
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/main_layout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@android:color/black" > <RelativeLayout android:id="@+id/main_panel" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_toLeftOf="@+id/btn_gripper_hide" android:background="#ffffff00" > <FrameLayout android:id="@+id/list_view" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_toEndOf="@+id/btn_list" android:background="@android:color/black" > <ListView android:id="@+id/friend_view" android:layout_width="fill_parent" android:layout_height="fill_parent" /> <ListView android:id="@+id/achivement_view" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </FrameLayout> <LinearLayout android:id="@+id/btn_list" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:background="@android:color/black" android:orientation="horizontal" > <Button android:id="@+id/btn_achivement" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" android:text="成就" /> <Button android:id="@+id/btn_friend" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" android:text="好友" /> <Button android:id="@+id/btn_more" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" android:text="更多" /> </LinearLayout> </RelativeLayout> <ImageView android:id="@+id/btn_gripper_hide" android:layout_width="20dp" android:layout_height="fill_parent" android:layout_alignParentRight="true" /> <ImageView android:id="@+id/touch_mask" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentRight="true" /> </RelativeLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:paddingTop="0dip" android:background="@android:color/black" > <FrameLayout android:layout_width="70dip" android:layout_height="70dip" android:layout_gravity="left" android:gravity="right" android:paddingBottom="5dip" android:paddingLeft="5dip" android:paddingRight="5dip" android:paddingTop="5dip" > <ImageView android:id="@+id/grid_item_img" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:scaleType="centerCrop" android:src="/blog_article/@drawable/anyshare_content_music_grid_item_bg/index.html" /> <ImageView android:id="@+id/grid_item_shared" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:background="#77e0e0e0" android:visibility="invisible" /> </FrameLayout> <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="left|center_vertical" android:gravity="left|center_vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="left|center_vertical" android:layout_marginRight="40dip" android:gravity="left|center_vertical" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:id="@+id/grid_music_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="0dip" android:layout_weight="1" android:gravity="left|center_vertical" android:singleLine="true" android:textColor="#ff7c7c7c" android:textSize="18sp" /> <TextView android:id="@+id/grid_music_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right|center_vertical" android:layout_weight="0" android:gravity="right" android:singleLine="true" android:textColor="#ff7c7c7c" android:textSize="13sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:id="@+id/grid_music_artist" android:layout_width="0dip" android:layout_height="wrap_content" android:layout_gravity="left|center_vertical" android:layout_weight="1" android:gravity="left" android:singleLine="true" android:maxLines="2" android:textColor="#ff7c7c7c" android:textSize="13sp" /> </LinearLayout> </LinearLayout> <ImageView android:id="@+id/grid_item_check" android:layout_width="30dip" android:layout_height="30dip" android:layout_gravity="right|center_vertical" android:paddingBottom="0dip" android:paddingRight="10dip" android:src="/blog_article/@drawable/anyshare_photo_check_on/index.html" /> </FrameLayout> </LinearLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/main_layout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@android:color/black" > <FrameLayout android:id="@+id/mainview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> <ImageView android:id="@+id/viewtag" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentRight="true" /> </RelativeLayout>