线程的常用方法
- package thread;
- /*
- 测试 Thread 类中的常用方法:
- 1.start()
- 2.run(): 重写 Thread 方法, 将线程要执行的操作声明在方法中
- 3.Thread.currentThread(): 静态方法, 返回执行当前代码的线程
- 4.getName(): 获取当前线程的名字
- 5.setName(): 设置当前线程的名字
- 6.yield(): 当前线程交出 CPU 执行权
- 7.join(): 在线程 a 中调用线程 b 的 join 方法, 此时线程 a 进入阻塞态, 直到线程 b 完全执行完后, a 才结束阻塞状态
- 8.stop(): 强制结束当期线程生命期, 不推荐使用
- 9.Thread.sleep(long millitime): 静态方法让当前线程睡眠指定毫秒数
- 10.isAlive():
- 线程的优先级
- 1.
- MAX_PRIORITY = 10
- NORM_PRIORITY = 5 默认优先级
- Min_PRIORITY = 1
- 2. 设置当前线程的优先级
- getPriority(): 获取当前线程优先级
- setPriority(int p): 设置~
- 说明: 高优先级的线程要抢占低优先级现场的 CPU 执行权, 但只是从概率上讲, 并不意味着
- 只有当高优先级线程执行完以后, 低优先级线程才执行
- @author zsben
- @create 2020-01-03 10:35
- */
- class HelloThread extends Thread{
- @Override
- public void run() {
- for(int i=0;i<100;i++) {
- if (i % 2 == 0) {
- try {
- sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName() + ":" + i + ","+this.getPriority());
- }
- if(i%20==0)
- this.yield();// 当前执行的线程交出执行权
- }
- }
- public HelloThread(String name){
- super(name);
- }
- public HelloThread(){
- super();
- }
- }
- public class ThreadMethodTest {
- public static void main(String[] args) {
- Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
- HelloThread helloThread = new HelloThread();
- //HelloThread helloThread1 = new HelloThread("thread2");
- helloThread.setName("thread1");
- helloThread.setPriority(Thread.MAX_PRIORITY);// 设置优先级
- helloThread.start();
- //helloThread1.start();
- // 给主线程命名
- Thread.currentThread().setName("main");
- for(int i=0;i<100;i++) {
- if (i % 2 == 0) {
- System.out.println(Thread.currentThread().getName() + ":" + i);
- }
- if(i==20) {
- try {
- helloThread.join();// 让 helloThread 线程先执行
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- System.out.println(helloThread.isAlive());
- }
- }
线程的生命周期
/*
线程生命周期: sleep(time),join()
sleep() 时间到, join() 结束 |--->-------- 阻塞 ------<---| 等待同步锁, wait()
获得同步锁, notify() | | suspend() 已被废弃
resume() 已被废弃 | 获取 CPU 执行权 |
新建 -----------------> 就绪 <----------------------> 运行 -------------------> 死亡
start() 失去 CPU 执行权或 yield() run() 执行完, stop(),
出现 Error 或异常且没处理
*/
来源: http://www.bubuko.com/infodetail-3364843.html