Android studio 简单的多线程

运行效果

运行效果

文件结构

文件结构

主要代码

MainActivity

package cn.edu.sicnu.threaddemo;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.lang.ref.WeakReference;
import java.security.PublicKey;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    TextView textView;
    ProgressBar progressBar;
    MyAsyncTask myAsyncTask;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        progressBar = findViewById(R.id.progressBar);
    }

    static class MyAsyncTask extends AsyncTask<Integer,Integer,Integer>{

        WeakReference<MainActivity> weakReference;

        public MyAsyncTask(MainActivity activity){
            weakReference = new WeakReference<MainActivity>(activity);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            MainActivity activity = weakReference.get();
            if (activity!=null) activity.progressBar.setProgress(0);
            Log.d(TAG, "onPreExecute: ");
        }

        @Override
        protected Integer doInBackground(Integer... integers) {
            int sum = 0;
            for(int i = 1; i < 100; i++) {
                try {
                    Log.d(TAG, "doInBackground: " + Thread.currentThread().getName());
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sum += i;
                publishProgress(i);
                if(isCancelled()) break;
            }
           return -1;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            Log.d(TAG, "onProgressUpdate: ");
            MainActivity activity = weakReference.get();
            if (activity!=null) {
                activity.textView.setText("progress"+values[0]);
                activity.progressBar.setProgress(values[0]);

            }
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            MainActivity activity = weakReference.get();
            if (activity!=null) activity.textView.setText("cancel!!!!");
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            Log.d(TAG, "onPostExecute: ");
            MainActivity activity = weakReference.get();
            if (activity!=null) {
                activity.textView.setText("congratulation!!!finished");
                activity.progressBar.setProgress(0);

            }

        }
    }


    public void calculate(View v) {
        myAsyncTask = new MyAsyncTask(this);
        myAsyncTask.execute(0);
    }

    public void stop(View v){
        myAsyncTask.cancel(true);
    }


//    private MyHandler handler = new MyHandler(this);
//    private Handler handler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//
//            switch (msg.what){
//                case 0:
//                    textView.setText("progress:"+msg.arg1);
//
//                    break;
//                case 1:
//                    textView.setText("congratulation!!!finished"+msg.what);
//
//                    break;
//            }
//            Log.d(TAG, "handleMessage: "+Thread.currentThread().getName());
//        }
//    };
//
//    static class MyHandler extends Handler{
//
//        WeakReference<MainActivity> weakReference;
//
//        public MyHandler(MainActivity activity){
//            this.weakReference = new WeakReference<MainActivity>(activity);
//        }
//
        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//
//            MainActivity activity = weakReference.get();
//            if (activity == null) return;;
//
//            switch (msg.what){
//                case 0:
//                    activity.textView.setText("progress:"+msg.arg1);
//
//                    break;
//                case 1:
//                    activity.textView.setText("congratulation!!!finished"+msg.what);
//
//                    break;
//            }
//            Log.d(TAG, "handleMessage: "+Thread.currentThread().getName());
//        }
//    }


//
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                int sum = 0;
//                for(int i = 1; i < 100; i++){
//                    try {
//                        Log.d(TAG, "run: "+Thread.currentThread().getName());
//                        Thread.sleep(100);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    sum += i;
//                    final int j = i;
//                    handler.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            textView.setText("progress:"+j);
//                        }
//                    });
                    Message msg = handler.obtainMessage();
                    msg.what = 0;
                    msg.arg1 = i;
                    handler.sendMessage(msg);
//                }
//
//                handler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        textView.setText("congratulation!!!finished");
//                    }
//                });

                Message msg = handler.obtainMessage();
                msg.what = 1;
                handler.sendMessage(msg);
//            }
//        }).start();
//
//
//
//    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="cn.edu.sicnu.threaddemo.MainActivity"
    tools:layout_editor_absoluteY="81dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="26dp"
        android:text="Hello World!"
        app:layout_constraintBottom_toTopOf="@+id/button2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="27dp"
        android:layout_marginEnd="53dp"
        android:onClick="calculate"
        android:text="start"
        app:layout_constraintBottom_toTopOf="@+id/progressBar"
        app:layout_constraintEnd_toEndOf="@+id/textView" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_marginBottom="105dp"
        android:layout_marginEnd="11dp"
        android:layout_marginStart="11dp"
        android:max="100"
        android:progress="0"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="66dp"
        android:layout_marginStart="64dp"
        android:onClick="stop"
        android:text="stop"
        app:layout_constraintBaseline_toBaselineOf="@+id/button"
        app:layout_constraintEnd_toEndOf="@+id/progressBar"
        app:layout_constraintStart_toStartOf="@+id/textView" />

</android.support.constraint.ConstraintLayout>
  • 0
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值