Specifying the Code to Run on a Thread - المعالجة الموازية

في هذا الدرس سوف نرى كيف ينفذ Runnable وتشغيل الكود في thread منفصل , نستطيع ارسال runnable وربطه مع thread ويتم تشغيله , كل واحد من runnable يسمى task

 thread و runnable هي كلاس بسيط محدود القوة ولكنه يعتبر الاساس للاكثر قوه في نظام الاندرويد مثل handler , acyncTask , intentservice و الrunnable هي الاساس ايضا الى كلاس ThresdPoolExecutor (هو كلاس يدير عملية thread و مهام Queue و يستطيع تشغيل multiple thread متوازية )

تعريف runnable 

اما من خلال تعريف كلاس وتضمينه داخلة 

public class PhotoDecodeRunnable implements Runnable {
    ...
    @Override
    public void run() {
        /*
         * Code you want to run on the thread goes here
         */
        ...
    }
    ...
}

او من خلال استخدام lambda في لغه كوتلن:

Runnable  { * Code you want to run on the thread goes here   }  
 لا يمكن الوصول الى ui من داخل runnable وانما يتم الوصول بطريقه تقنيه
 Communicate with the UI Thread.

 في بدايه التشغيل داخل دالة run يمكن استخدام Process.setThreadPriority() with THREAD_PRIORITY_BACKGROUND
لاخذ اولويه الشتغيل في الخلفية 

class PhotoDecodeRunnable implements Runnable {
...
    /*
     * Defines the code to run for this task.
     */
    @Override
    public void run() {
        // Moves the current Thread into the background
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND)
        ...
        /*
         * Stores the current Thread in the PhotoTask instance,
         * so that the instance
         * can interrupt the Thread.
         */
        mPhotoTask.setImageDecodeThread(Thread.currentThread());
        ...
    }
...
}

 

تعليقات

المشاركات الشائعة من هذه المدونة

مقدمة عن Dagger 2

local function

Architecture patterns in Android part 1 - معماريه كتابه الكود في الاندرويد جزء 1