Java多线程(二)- 常用方法

来源:互联网 发布:python修改文件内容 编辑:程序博客网 时间:2024/05/29 14:27

线程的常用方法有

  • start()
  • run()
  • sleep(int millsecond)
  • isAlive()
  • currentThread()
  • interrupt()

1.start方法

线程调用该方法启动线程,线程从新建队列进入就绪队列排队,一旦轮到它来享用CPU资源时,就可以脱离创建它的线程独立开始进行自己的生命周期了。当线程第二次调用start方法是,会抛出IlleglThreadStateException异常。

2.run方法

用户需要自己创建自己的Thread类的子类,并重写run方法。

3.sleep(int millsecond)方法

想成的调度执行是按照其优先级高低顺序进行的,当高级别的线程未死亡时,地级县城没有机会获得CPU资源。有时优先级高的线程需要优先级低的线程做一些工作来配合它,所以可以通过在run方法中执行此方法将系统资源让出。如果休眠状态被打断,JVM就抛出InterruptedException异常。因此必须对异常进行处理。

4.isAlive方法

线程处于“新建”状态以及死亡状态(实体内存被释放),此方法返回值为false。在该线程得到CPU资源、run方法开始执行后,返回值为true。

5.currentThread方法

是Thread类中的类方法,可以用类名调用,该方法返回当前正在使用的CPU资源的线程。

6.interrupt方法

用来唤醒休眠线程。当一些线程调用sleep方法处于休眠状态时,一个占有CPU资源的线程可以让休眠的线程调用interrupt方法唤醒自己,即导致休眠线程发生InterruptException异常,从而结束休眠,重新排队等待CPU资源。

package test;public class ClassRoom implements Runnable {    Thread student,teacher;    public ClassRoom() {        teacher = new Thread(this);        student = new Thread(this);        teacher.setName("Mr.Fa");        student.setName("Miss.Song");    }    @Override    public void run() {        if (Thread.currentThread() == student) {            try {                System.out.println(student.getName()+"正在睡觉");                Thread.sleep(1000*60*60);            } catch (InterruptedException e) {                System.out.println(student.getName()+"被叫醒!!");            }            System.out.println("开始写代码.......");        }else if (Thread.currentThread()==teacher) {            for(int i = 0;i<3;i++){                try {                    System.out.println(teacher.getName()+"来了......赶快开始写代码");                    Thread.sleep(500);                } catch (InterruptedException e) {                }            }            student.interrupt();        }    }}
package test;public class Example1_2 {    public static void main(String[] args) {        ClassRoom classRoom = new ClassRoom();        classRoom.student.start();        classRoom.teacher.start();    }}

Miss.Song正在睡觉
Mr.Fa来了……赶快开始写代码
Mr.Fa来了……赶快开始写代码
Mr.Fa来了……赶快开始写代码
Miss.Song被叫醒!!
开始写代码…….

0 0