简体   繁体   English

如何在android中同时运行2个线程

[英]How to Run 2 threads simultaneously in android

I am new to android programming.Sorry if this type of question have been asked before. 我是android编程的新手。如果之前已经问过这类问题。 I am getting trouble while creating threads.In my code, I have initialized int i=500; 我在创建线程时遇到麻烦。在我的代码中,我初始化了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 并且在我的第一个线程t1中,我想增加t1的值if(i<5000)并且在我的线程t2上想要检查t2的值减去的条件if(i>0)请帮助...提前致谢

Here is the plain java Thread implementation for android as you required for this specific increment/decrement problem... 这是Android的普通java Thread实现,因为你需要这个特定的增量/减量问题...

// 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. 更新:更新源以使用AtomicInteger而不是plain int来避免并发访问问题。

You can do this by using AsyncTask: http://developer.android.com/reference/android/os/AsyncTask.html 您可以使用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. 请注意,在Android上的某些版本中,AsyncTask在单个线程上执行。 If you need to execute in paralell this need to be set on the task, from the documentation: 如果你需要在paralell中执行,那么需要在文档中设置任务:

When first introduced, AsyncTasks were executed serially on a single background thread. 首次引入时,AsyncTasks在单个后台线程上串行执行。 Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. 从DONUT开始,这被改为一个线程池,允许多个任务并行运行。 Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution. 从HONEYCOMB开始,任务在单个线程上执行,以避免由并行执行引起的常见应用程序错误。 If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR. 如果您真的想要并行执行,可以使用THREAD_POOL_EXECUTOR调用executeOnExecutor(java.util.concurrent.Executor,Object [])。

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. 覆盖“doInBackground()”方法中的代码在不同的线程上执行。 If you need to modify some UI before or after the task is done you can easily override onPreExecute and onPostExecute. 如果您需要在任务完成之前或之后修改某些UI,您可以轻松覆盖onPreExecute和onPostExecute。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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