@IT·互联网

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

2020-08-15  本文已影响0人  进击的包籽

1.操作系统层面,五种状态

五种状态 各种状态.png

2.Java层面,六种状态

源码里可以找到

3.不同状态关系

Java线程状态

4.不同状态调用的方法

不同状态直接的切换

5.运行代码尝试一下

//创建, Thread.State.NEW
Thread thread1 = new Thread() {
    @Override
    public void run() {
        super.run();
    }
};
 
//线程一直在运行Thread.State.RUNNABLE
Thread thread2 = new Thread() {
    @Override
    public void run() {
        while (true) {
 
        }
    }
};
thread2.start();
 
 
//Thread.State.TERMINATED
Thread thread3 = new Thread() {
    @Override
    public void run() {
        Log.d(TAG, "thread run");
    }
};
thread3.start();
 
//Thread.State.TIMED_WAITING
final Thread thread4 = new Thread() {
    @Override
    public void run() {
        synchronized (object) {
            try {
                TimeUnit.SECONDS.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
};
thread4.start();
 
//Thread.State.WAITING
Thread thread5 = new Thread() {
    @Override
    public void run() {
        try {
            thread4.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};
thread5.start();
 
//Thread.State.BLOCKED
Thread thread6 = new Thread() {
    @Override
    public void run() {
        synchronized (object) {
            try {
                TimeUnit.SECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
};
thread6.start();
 
try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}
 
Log.d(TAG,"thread1 state: "+thread1.getState());
Log.d(TAG,"thread2 state: "+thread2.getState());
Log.d(TAG,"thread3 state: "+thread3.getState());
Log.d(TAG,"thread4 state: "+thread4.getState());
Log.d(TAG,"thread5 state: "+thread5.getState());
Log.d(TAG,"thread6 state: "+thread6.getState());
上一篇 下一篇

猜你喜欢

热点阅读