程序员

Android 开发也要掌握的Java并发知识 - 多线程基础1

2020-08-15  本文已影响0人  进击的包籽
1.线程创建的两种方法:
线程创建的两种方法
2.线程的启动运行
3.线程的停止
4.线程休眠
TimeUnit实现
MyThread myThread = new MyThread();
myThread.setName("MyThread");
myThread.start();
//主线程休眠5秒
try {
    TimeUnit.SECONDS.sleep(5);
    myThread.interrupt();
} catch (InterruptedException e) {
    e.printStackTrace();
}


MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable,"myRunnable");
thread.start();
//主线程休眠5秒
try {
    Thread.sleep(5000);
    thread.interrupt();
} catch (InterruptedException e) {
    e.printStackTrace();
}


/**
 * 继承Thread类
 */
class MyThread extends Thread {
    @Override
    public void run() {
        while (true) {
            //打断线程
            if (interrupted()) {
                //这里 Thread.currentThread().isInterrupted() 会是false -> true,但在interrupted()后,true -> false,被清除了标记
                Log.d(TAG, Thread.currentThread().getName() + ":interrupted() : " +  Thread.currentThread().isInterrupted());
                break;
            }
            Log.d(TAG, Thread.currentThread().getName() + ":baozi");
        }
    }
}

/**
 * 实现Runnable接口
 */
class MyRunnable implements Runnable {
    @Override
    public void run() {
        while (true) {
            //打断线程
            if (Thread.currentThread().isInterrupted()) {
                //这里 Thread.currentThread().isInterrupted() 会是false -> true
                Log.d(TAG, Thread.currentThread().getName() + ":interrupted(): " + Thread.currentThread().isInterrupted());
                break;
            }
            Log.d(TAG, Thread.currentThread().getName() + ":baozi");
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读