zoukankan      html  css  js  c++  java
  • review37

    线程的常用方法

    1.start()

    线程调用该方法将启动线程,使之从新建状态进入就绪队列排队。

    2.run()

    3.sleep()

    4.isAlive()

    线程处于新建状态时,线程调用isAlive()方法返回false。

    public class ClassRoom implements Runnable {
        Thread student, teacher;
        ClassRoom()
        {
            teacher = new Thread(this);
            student = new Thread(this);
            teacher.setName("王教授");
            student.setName("张三");
        }
    
        @Override
        public void run() {
            // TODO Auto-generated method stub
            if(Thread.currentThread() == student)
            {
                System.out.println(student.getName() + "正在睡觉, 不听课");
                try {
                    Thread.sleep(1000*100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    System.out.println(student.getName() + "被老师叫醒了");
                }
            }
            else if(Thread.currentThread() == teacher)
            {
                for(int i = 1; i <= 3; i++){
                    System.out.println("上课");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                student.interrupt();
            }
        }
    
    }

    运行

    public class Test03 {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            ClassRoom room6501 = new ClassRoom();
            room6501.student.start();
            room6501.teacher.start();
        }
    
    }

    运行结果如下所示:

  • 相关阅读:
    2018
    线程的五大状态
    SQL 列转行与行转列
    python中元组(tuple)的拆包unkacping
    python字典的相关操作总结
    C语言使用typedef进行类型重定义
    C++中namespace的用法理解
    ping: unknown host 解决办法
    go环境变量配置liteide配置
    svn出现Authorization failed
  • 原文地址:https://www.cnblogs.com/liaoxiaolao/p/9489123.html
Copyright © 2011-2022 走看看