简体   繁体   中英

How to Run 2 threads simultaneously in android

I am new to android programming.Sorry if this type of question have been asked before. I am getting trouble while creating threads.In my code, I have initialized int i=500; and in my first thread t1, i want to increment the value of t1 if(i<5000) and also on my thread t2 want to check the condition where the value of t2 is decremented if(i>0) Please help...Thanks in advance

Here is the plain java Thread implementation for android as you required for this specific increment/decrement problem...

// class lass level declarations
private static int DEF_VALUE = 500;
private static int MIN_VALUE = 0;
private static int MAX_VALUE = 1000;

private AtomicInteger i = new AtomicInteger(DEF_VALUE);
private Thread t1 = null;
private Thread t2 = null;

private void initThreads() {
    Log.i(TAG, "Initializing Threads...");

    t1 = new Thread(new Runnable() {

        @Override
        public void run() {
            Log.i(TAG, "Starting T1.");
            while (i.get() < MAX_VALUE) {
                i.incrementAndGet();
                Log.d(TAG, String.format("Incremented by T1, i = %d", i.get()));
            }
            Log.i(TAG, "Finishing T1.");
        }
    });

    t2 = new Thread(new Runnable() {

        @Override
        public void run() {
            Log.i(TAG, "Starting T1.");
            while (i.get() > MIN_VALUE) {
                i.decrementAndGet();
                Log.d(TAG, String.format("Decremented by T2, i =  %d", i.get()));
            }
            Log.i(TAG, "Finishing T2.");
        }
    });

    t1.start();
    t2.start();
}

Hope this helps...:)

Update: Source updated to use AtomicInteger instead of plain int to avoid concurrent access issues.

You can do this by using AsyncTask: http://developer.android.com/reference/android/os/AsyncTask.html

Do note that in some versions on Android, AsyncTask is executed on a single thread. If you need to execute in paralell this need to be set on the task, from the documentation:

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution. If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.

In addition, you will run into concurrency issues, so you should take steps to handle them.

It might look like this:

public class DoingTwoThings {

private AsyncTask<Void, Void, Void> taskA;
private AsyncTask<Void, Void, Void> taskB;
private volatile int i;

public DoingTwoThings() {
    createTaskA();
    createTaskB();
    startTasks();
}

private void createTaskA() {
    taskA = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            doInBackgroundA();
            return null;
        }
    };
}

private void doInBackgroundA() {
    while (i < 5000) {
        i++;
    }
}

private void createTaskB() {
    taskB = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            doInBackGroundB();
            return null;
        }
    };
}

private void doInBackGroundB() {
    while (i > 0) {
        i--;
    }
}

private void startTasks() {
    // AsyncTasks executed one one thread in Honeycomb+ unless executed in thread pool manually
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        taskA.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        taskB.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    } else {
        taskA.execute();
        taskB.execute();
    }
}}

The code in the overriden "doInBackground()" methods are executed on a different thread. If you need to modify some UI before or after the task is done you can easily override onPreExecute and onPostExecute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM