Android知识巩固—Java多线程基础

线程:程序执行流的最小单元【可以理解为:进程中独立运行的子任务】。

多线程优点:最大限度的利用CPU的空闲时间来处理其他任务。

创建线程

继承Thread类

public class MainActivity extends AppCompatActivity {
     

    public static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
     
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyThread myThread=new MyThread();
        myThread.start();
    }

    class MyThread extends Thread {
     
        @Override
        public void run() {
     
            super.run();
            Log.i(TAG, "hello world !!");
        }
    }
}

实现Runnable接口

public class MainActivity extends AppCompatActivity {
     

    public static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
     
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Runnable runnable = new MyRunnable();
        new Thread(runnable).start();
    }

    class MyRunnable implements Runnable {
     
        @Override
        public void run() {
     
            Log.i(TAG, "Hello world !!");
        }
    }
}

上述两种创建方式,工作时性质一样。但是建议使用实现Runable接口方式。解决单继承的局限性。

线程运行结果与执行顺序无关

线程的调度是由CPU决定,CPU执行子任务时间具有不确定性。

public class MainActivity extends AppCompatActivity {
     

    public static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
     
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
     
            threads[i] = new MyThread("MyThread:" + i);
        }
        for (Thread thread : threads) {
     
            thread.start();
        }
    }

    class MyThread extends Thread {
     

        public MyThread(String name) {
     
            super(name);
        }

        @Override
        public void run() {
     
            try {
     
                Thread.sleep(1000);
                Log.i(TAG, Thread.currentThread().getName());
            } catch (InterruptedException e) {
     
                e.printStackTrace();
            }
        }
    }
}

以上10个线程,代码按照顺序执行,但是结果可以看出没有按照顺序执行,而且多次执行结果基本不同。

2019-01-01 21:35:40.635 14559-14598/com.example.testdemo I/MainActivity: MyThread:2
2019-01-01 21:35:40.635 14559-14597/com.example.testdemo I/MainActivity: MyThread:1
2019-01-01 21:35:40.635 14559-14599/com.example.testdemo I/MainActivity: MyThread:3
2019-01-01 21:35:40.636 14559-14600/com.example.testdemo I/MainActivity: MyThread:4
2019-01-01 21:35:40.636 14559-14601/com.example.testdemo I/MainActivity: MyThread:5
2019-01-01 21:35:40.636 14559-14602/com.example.testdemo I/MainActivity: MyThread:6
2019-01-01 21:35:40.636 14559-14603/com.example.testdemo I/MainActivity: MyThread:7
2019-01-01 21:35:40.636 14559-14596/com.example.testdemo I/MainActivity: MyThread:0
2019-01-01 21:35:40.636 14559-14605/com.example.testdemo I/MainActivity: MyThread:9
2019-01-01 21:35:40.637 14559-14604/com.example.testdemo I/MainActivity: MyThread:8

线程实例变量与安全问题

线程之间变量有共享与不共享之分,共享理解为大家都使用同一份,不共享理解为每个单独持有一份。

共享数据情况

public class MainActivity extends AppCompatActivity {
     

    public static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
     
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Runnable runnable = new MyRunnable();
        Thread[] threads = new Thread[5];
        for (int i = 0; i < 5; i++) {
     
            threads[i] = new Thread(runnable, "thread:" + (i + 1));
        }
        for (Thread thread : threads) {
     
            thread.start();
        }
    }

    class MyRunnable implements Runnable {
     

        private int count = 5;
        
        @Override
        public void run() {
     
            Log.i(TAG, "" + Thread.currentThread().getName() + ",count:" + count--);
        }
    }
}
2019-01-01 21:44:09.746 15089-15108/? I/MainActivity: thread:3,count:5
2019-01-01 21:44:09.746 15089-15107/? I/MainActivity: thread:2,count:4
2019-01-01 21:44:09.746 15089-15110/? I/MainActivity: thread:5,count:3
2019-01-01 21:44:09.746 15089-15109/? I/MainActivity: thread:4,count:3
2019-01-01 21:44:09.747 15089-15106/? I/MainActivity: thread:1,count:2

从上结果可以看出,count变量是共享的。但是也发现了一点thread:4 与 thread:5 打印值一样,该现象就是我们通常称为的脏数据【多线程对同一变量进行读写操作不同步产生】。

解决方案在访问变量方法中增加synchronized关键字

class MyRunnable implements Runnable {
     

        private int count = 5;

        @Override
        public synchronized void run() {
     
            Log.i(TAG, "" + Thread.currentThread().getName() + ",count:" + count--);
        }
    }
2019-01-01 21:45:37.676 15323-15340/com.example.testdemo I/MainActivity: thread:1,count:5
2019-01-01 21:45:37.676 15323-15341/com.example.testdemo I/MainActivity: thread:2,count:4
2019-01-01 21:45:37.676 15323-15342/com.example.testdemo I/MainActivity: thread:3,count:3
2019-01-01 21:45:37.677 15323-15343/com.example.testdemo I/MainActivity: thread:4,count:2
2019-01-01 21:45:37.677 15323-15344/com.example.testdemo I/MainActivity: thread:5,count:1

每次打印count都是正常递减,这里解释一下synchronized关键字,含有synchronized关键字的这个方法称为“互斥区” 或“临界区”,只有获得这个关键字对应的锁才能执行方法体,方法体执行完自动会释放锁。

停止线程

终止正在运行的线程方法有三种:

使用退出标志,使线程正常的执行完run方法终止。

使用interrupt方法,使线程异常,线程进行捕获或抛异常,正常执行完run方法终止。

使用stop方法强制退出。

使用退出标志方法

public class MainActivity extends AppCompatActivity {
     

    public static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
     
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyStopThread thread = new MyStopThread("1");
        thread.start();
        try {
     
            Thread.sleep(1);
        } catch (InterruptedException e) {
     
            e.printStackTrace();
        }
        thread.stopThread();
    }

    class MyStopThread extends Thread {
     
        private boolean tag = true;

        public MyStopThread(String name) {
     
            super(name);
        }

        @Override
        public void run() {
     
            Log.i(TAG, Thread.currentThread().getName() + ":线程开始运行!");
            int i = 0;
            while (tag) {
     
                Log.i(TAG, "" + (i++));
            }
            Log.i(TAG, "我停止了! timer:" + System.currentTimeMillis());
        }

        public void stopThread() {
     
            Log.i(TAG, Thread.currentThread().getName() + ":线程设置了停止! timer:" + System.currentTimeMillis());
            this.tag = false;
        }
    }
}
2019-01-02 14:16:38.219 8180-8202/? I/MainActivity: 1:线程开始运行!
2019-01-02 14:16:38.219 8180-8202/? I/MainActivity: 0
2019-01-02 14:16:38.219 8180-8202/? I/MainActivity: 1
2019-01-02 14:16:38.219 8180-8202/? I/MainActivity: 2
2019-01-02 14:16:38.219 8180-8202/? I/MainActivity: 3
2019-01-02 14:16:38.219 8180-8202/? I/MainActivity: 4
2019-01-02 14:16:38.220 8180-8202/? I/MainActivity: 5
2019-01-02 14:16:38.220 8180-8202/? I/MainActivity: 6
2019-01-02 14:16:38.220 8180-8202/? I/MainActivity: 7
2019-01-02 14:16:38.220 8180-8202/? I/MainActivity: 8
2019-01-02 14:16:38.220 8180-8202/? I/MainActivity: 9
2019-01-02 14:16:38.220 8180-8202/? I/MainActivity: 10
2019-01-02 14:16:38.220 8180-8202/? I/MainActivity: 11
2019-01-02 14:16:38.220 8180-8202/? I/MainActivity: 12
2019-01-02 14:16:38.220 8180-8202/? I/MainActivity: 13
2019-01-02 14:16:38.220 8180-8202/? I/MainActivity: 14
2019-01-02 14:16:38.220 8180-8202/? I/MainActivity: 15
2019-01-02 14:16:38.220 8180-8202/? I/MainActivity: 16
2019-01-02 14:16:38.220 8180-8202/? I/MainActivity: 17
2019-01-02 14:16:38.220 8180-8180/? I/MainActivity: main:线程设置了停止! timer:1546409798220
2019-01-02 14:16:38.222 8180-8202/? I/MainActivity: 18
2019-01-02 14:16:38.222 8180-8202/? I/MainActivity: 我停止了! timer:1546409798222

1中启动了一个while循环,一直打印i的累加值。main线程在sleep 1ms后设置Thread 1停止标志。Thread 1 while循环判断条件不符合正常执行完run方法结束。从中可以看出设置完停止标志后17还是正常打印,原因是因为while方法体中是原子操作,不能直接打断。

在使用终止线程方法一时,个人建议代码这么修改更符合Java API规范也避免线程死循环问题。

public class MainActivity extends AppCompatActivity {
     

    public static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
     
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyStopThread thread = new MyStopThread("1");
        thread.start();
        try {
     
            Thread.sleep(1);
        } catch (InterruptedException e) {
     
            e.printStackTrace();
        }
        thread.interrupt();
    }

    class MyStopThread extends Thread {
     
        public MyStopThread(String name) {
     
            super(name);
        }

        @Override
        public void run() {
     
            Log.i(TAG, Thread.currentThread().getName() + ":线程开始运行!");
            while (!isInterrupted()) {
     

            }
            Log.i(TAG, "我停止了! timer:" + System.currentTimeMillis());
        }
    }
}

2019-01-02 14:35:25.026 9860-9886/com.example.testdemo I/MainActivity: 1:线程开始运行!
2019-01-02 14:35:25.028 9860-9886/com.example.testdemo I/MainActivity: 我停止了! timer:1546410925028

使用interrupt方法

public class MainActivity extends AppCompatActivity {
     

    public static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
     
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyStopThread thread = new MyStopThread("1");
        thread.start();
        try {
     
            Thread.sleep(1);
        } catch (InterruptedException e) {
     
            e.printStackTrace();
        }
        thread.interrupt();
    }

    class MyStopThread extends Thread {
     
        public MyStopThread(String name) {
     
            super(name);
        }

        @Override
        public void run() {
     
            Log.i(TAG, Thread.currentThread().getName() + ":线程开始运行!");
            for (int i = 0; i < 1000; i++) {
     
                try {
     
                    Thread.sleep(0);
                    Log.i(TAG, (i + 1) + "");
                } catch (InterruptedException e) {
     
                    Log.i(TAG, Thread.currentThread().getName() + "线程捕获异常,退出循环!");
                    break;
                }
            }
            Log.i(TAG, "我停止了! timer:" + System.currentTimeMillis());
        }
    }
}
2019-01-02 14:38:39.396 10038-10074/com.example.testdemo I/MainActivity: 1:线程开始运行!
2019-01-02 14:38:39.396 10038-10074/com.example.testdemo I/MainActivity: 1
2019-01-02 14:38:39.396 10038-10074/com.example.testdemo I/MainActivity: 2
2019-01-02 14:38:39.396 10038-10074/com.example.testdemo I/MainActivity: 3
2019-01-02 14:38:39.396 10038-10074/com.example.testdemo I/MainActivity: 4
2019-01-02 14:38:39.396 10038-10074/com.example.testdemo I/MainActivity: 5
2019-01-02 14:38:39.396 10038-10074/com.example.testdemo I/MainActivity: 6
2019-01-02 14:38:39.396 10038-10074/com.example.testdemo I/MainActivity: 7
2019-01-02 14:38:39.396 10038-10074/com.example.testdemo I/MainActivity: 8
2019-01-02 14:38:39.396 10038-10074/com.example.testdemo I/MainActivity: 9
2019-01-02 14:38:39.396 10038-10074/com.example.testdemo I/MainActivity: 10
2019-01-02 14:38:39.396 10038-10074/com.example.testdemo I/MainActivity: 11
2019-01-02 14:38:39.397 10038-10074/com.example.testdemo I/MainActivity: 12
2019-01-02 14:38:39.397 10038-10074/com.example.testdemo I/MainActivity: 13
2019-01-02 14:38:39.397 10038-10074/com.example.testdemo I/MainActivity: 14
2019-01-02 14:38:39.397 10038-10074/com.example.testdemo I/MainActivity: 15
2019-01-02 14:38:39.397 10038-10074/com.example.testdemo I/MainActivity: 16
2019-01-02 14:38:39.397 10038-10074/com.example.testdemo I/MainActivity: 17
2019-01-02 14:38:39.398 10038-10074/com.example.testdemo I/MainActivity: 18
2019-01-02 14:38:39.398 10038-10074/com.example.testdemo I/MainActivity: 1线程捕获异常,退出循环!
2019-01-02 14:38:39.398 10038-10074/com.example.testdemo I/MainActivity: 我停止了! timer:1546411119398

从上可以看出线程正常退出,但是发现一点循环结构体后面一句打印也打印了,解决这个问题的方案有两个:

异常法

public class MainActivity extends AppCompatActivity {
     

    public static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
     
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyStopThread thread = new MyStopThread("1");
        thread.start();
        try {
     
            Thread.sleep(1);
        } catch (InterruptedException e) {
     
            e.printStackTrace();
        }
        thread.interrupt();
    }

    class MyStopThread extends Thread {
     
        public MyStopThread(String name) {
     
            super(name);
        }

        @Override
        public void run() {
     
            Log.i(TAG, Thread.currentThread().getName() + ":线程开始运行!");
            try {
     
                for (int i = 0; i < 1000; i++) {
     
                    if (Thread.currentThread().interrupted()) {
     
                        Log.i(TAG, Thread.currentThread().getName() + "线程停止状态!");
                        throw new InterruptedException();
                    }
                    Thread.sleep(0);
                    Log.i(TAG, (i + 1) + "");
                }
            } catch (InterruptedException e) {
     
                Log.i(TAG, Thread.currentThread().getName() + "线程捕获异常,退出循环!");
            }
            Log.i(TAG, "我停止了! timer:" + System.currentTimeMillis());
        }
    }
}
2019-01-02 14:46:58.201 12861-12888/com.example.testdemo I/MainActivity: 1:线程开始运行!
2019-01-02 14:46:58.201 12861-12888/com.example.testdemo I/MainActivity: 1
2019-01-02 14:46:58.201 12861-12888/com.example.testdemo I/MainActivity: 2
2019-01-02 14:46:58.201 12861-12888/com.example.testdemo I/MainActivity: 3
2019-01-02 14:46:58.201 12861-12888/com.example.testdemo I/MainActivity: 4
2019-01-02 14:46:58.201 12861-12888/com.example.testdemo I/MainActivity: 5
2019-01-02 14:46:58.201 12861-12888/com.example.testdemo I/MainActivity: 6
2019-01-02 14:46:58.201 12861-12888/com.example.testdemo I/MainActivity: 7
2019-01-02 14:46:58.201 12861-12888/com.example.testdemo I/MainActivity: 8
2019-01-02 14:46:58.201 12861-12888/com.example.testdemo I/MainActivity: 9
2019-01-02 14:46:58.201 12861-12888/com.example.testdemo I/MainActivity: 10
2019-01-02 14:46:58.201 12861-12888/com.example.testdemo I/MainActivity: 11
2019-01-02 14:46:58.201 12861-12888/com.example.testdemo I/MainActivity: 12
2019-01-02 14:46:58.201 12861-12888/com.example.testdemo I/MainActivity: 13
2019-01-02 14:46:58.201 12861-12888/com.example.testdemo I/MainActivity: 14
2019-01-02 14:46:58.201 12861-12888/com.example.testdemo I/MainActivity: 15
2019-01-02 14:46:58.202 12861-12888/com.example.testdemo I/MainActivity: 16
2019-01-02 14:46:58.202 12861-12888/com.example.testdemo I/MainActivity: 17
2019-01-02 14:46:58.202 12861-12888/com.example.testdemo I/MainActivity: 1线程停止状态!
2019-01-02 14:46:58.203 12861-12888/com.example.testdemo I/MainActivity: 1线程捕获异常,退出循环!
2019-01-02 14:46:58.203 12861-12888/com.example.testdemo I/MainActivity: 我停止了! timer:1546411618203

代码有两个关键点:

for循环外捕获异常【这是程序的关键点】

判断设置了interrupted标志则抛出异常。

return法

public class MainActivity extends AppCompatActivity {

    public static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyStopThread thread = new MyStopThread("1");
        thread.start();
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt();
    }

    class MyStopThread extends Thread {
        public MyStopThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            Log.i(TAG, Thread.currentThread().getName() + ":线程开始运行!");
            try {
                for (int i = 0; i < 1000; i++) {
                    Thread.sleep(0);
                    Log.i(TAG, (i + 1) + "");
                }
            } catch (InterruptedException e) {
                Log.i(TAG, Thread.currentThread().getName() + "线程捕获异常,退出循环!");
                e.printStackTrace();
                return;
            }
            Log.i(TAG, "我停止了! timer:" + System.currentTimeMillis());
        }
    }
}
2019-01-02 16:58:18.275 16496-16524/com.example.testdemo I/MainActivity: 1:线程开始运行!
2019-01-02 16:58:18.275 16496-16524/com.example.testdemo I/MainActivity: 1
2019-01-02 16:58:18.275 16496-16524/com.example.testdemo I/MainActivity: 2
2019-01-02 16:58:18.275 16496-16524/com.example.testdemo I/MainActivity: 3
2019-01-02 16:58:18.275 16496-16524/com.example.testdemo I/MainActivity: 4
2019-01-02 16:58:18.275 16496-16524/com.example.testdemo I/MainActivity: 5
2019-01-02 16:58:18.275 16496-16524/com.example.testdemo I/MainActivity: 6
2019-01-02 16:58:18.275 16496-16524/com.example.testdemo I/MainActivity: 7
2019-01-02 16:58:18.275 16496-16524/com.example.testdemo I/MainActivity: 8
2019-01-02 16:58:18.275 16496-16524/com.example.testdemo I/MainActivity: 9
2019-01-02 16:58:18.275 16496-16524/com.example.testdemo I/MainActivity: 10
2019-01-02 16:58:18.275 16496-16524/com.example.testdemo I/MainActivity: 11
2019-01-02 16:58:18.275 16496-16524/com.example.testdemo I/MainActivity: 12
2019-01-02 16:58:18.275 16496-16524/com.example.testdemo I/MainActivity: 13
2019-01-02 16:58:18.275 16496-16524/com.example.testdemo I/MainActivity: 14
2019-01-02 16:58:18.275 16496-16524/com.example.testdemo I/MainActivity: 15
2019-01-02 16:58:18.275 16496-16524/com.example.testdemo I/MainActivity: 16
2019-01-02 16:58:18.276 16496-16524/com.example.testdemo I/MainActivity: 17
2019-01-02 16:58:18.277 16496-16524/com.example.testdemo I/MainActivity: 18
2019-01-02 16:58:18.277 16496-16524/com.example.testdemo I/MainActivity: 1线程捕获异常,退出循环!

这个方法相对简单,也比较常用。两种方法结果都一样直接退出不进行后续工作,两种方法依据功能需求选择。

线程优先级

线程优先级范围为1-10,API提供等级分为:低(MIN_PRIORITY = 1),中(NORM_PRIORITY=5),高(MAX_PRIORITY=10)。

线程优先级有以下特点:

继承特性【线程A中启动线程B,线程B继承了A的优先级】;

随机性【线程调度的顺序不一定是根据优先级,具有随机性】;

public class MainActivity extends AppCompatActivity {

    public static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Thread thread1 = new MyStopThread("thread1");
        Thread thread2 = new MyStopThread("thread2");
        thread1.setPriority(Thread.MIN_PRIORITY);
        thread2.setPriority(Thread.MAX_PRIORITY);
        thread1.start();
        thread2.start();
    }

    class MyStopThread extends Thread {
        public MyStopThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                Log.i(TAG, Thread.currentThread().getName() + ",number:" + i + ",Priority:" + Thread.currentThread().getPriority());
            }
        }
    }
}
2019-01-02 17:17:04.587 17766-17793/? I/MainActivity: thread1,number:0,Priority:1
2019-01-02 17:17:04.587 17766-17794/? I/MainActivity: thread2,number:0,Priority:10
2019-01-02 17:17:04.587 17766-17793/? I/MainActivity: thread1,number:1,Priority:1
2019-01-02 17:17:04.587 17766-17794/? I/MainActivity: thread2,number:1,Priority:10
2019-01-02 17:17:04.587 17766-17793/? I/MainActivity: thread1,number:2,Priority:1
2019-01-02 17:17:04.587 17766-17794/? I/MainActivity: thread2,number:2,Priority:10
2019-01-02 17:17:04.587 17766-17793/? I/MainActivity: thread1,number:3,Priority:1
2019-01-02 17:17:04.587 17766-17794/? I/MainActivity: thread2,number:3,Priority:10
2019-01-02 17:17:04.587 17766-17793/? I/MainActivity: thread1,number:4,Priority:1
2019-01-02 17:17:04.587 17766-17794/? I/MainActivity: thread2,number:4,Priority:10
2019-01-02 17:17:04.587 17766-17793/? I/MainActivity: thread1,number:5,Priority:1
2019-01-02 17:17:04.587 17766-17794/? I/MainActivity: thread2,number:5,Priority:10
2019-01-02 17:17:04.587 17766-17793/? I/MainActivity: thread1,number:6,Priority:1
2019-01-02 17:17:04.587 17766-17794/? I/MainActivity: thread2,number:6,Priority:10
2019-01-02 17:17:04.587 17766-17793/? I/MainActivity: thread1,number:7,Priority:1
2019-01-02 17:17:04.587 17766-17794/? I/MainActivity: thread2,number:7,Priority:10
2019-01-02 17:17:04.587 17766-17793/? I/MainActivity: thread1,number:8,Priority:1
2019-01-02 17:17:04.587 17766-17794/? I/MainActivity: thread2,number:8,Priority:10
2019-01-02 17:17:04.587 17766-17793/? I/MainActivity: thread1,number:9,Priority:1
2019-01-02 17:17:04.587 17766-17794/? I/MainActivity: thread2,number:9,Priority:10

你可能感兴趣的:(Android随笔,个人知识巩固)