java多线程的常用方法

介绍一些多线程中的常用方法:

        //启动方法
        a.start();

        //返回代码正在被哪个线程调用的信息
        a.currentThread();

        //返回线程的名字
        a.currentThread().getName();

        //判断线程是否处于存活状态
        a.isAlive();

        //线程延迟 单位毫秒
        a.sleep();

        //取得线程的唯一标识
        a.getId();

 暂停继续:

//让线程以毫秒进入阻塞状态,等到时间一过,正常运行
a.sleep(300);

 suspend()和 resume()方法:

  线程的暂停和恢复,使用 suspend()方法使线程进入阻塞状态,不可以自动恢复,可使用resume()方法将线程唤醒。

yield()方法:

  yield()方法的作用是放弃当前CPU资源,将他让给其他的任务去使用,但是放弃的时间是不确定的,有可以刚刚放弃,马上又得到CPU的使用时间。

  下面写段代码举个例子:

不使用yield()方法执行:

public class Test01 extends Thread {

    @Override
    public void run() {
        super.run();
        long beginTime = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            System.out.println(i++);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("执行完成,用时:" + (endTime - beginTime) + "毫秒!");
    }


    public static void main(String[] args) {
        Test01 thread = new Test01();
        thread.start();
    }
}


//打印结果

9990
9992
9994
9996
9998
执行完成,用时:37毫秒!

使用yield()方法执行:

public class Test01 extends Thread {

    @Override
    public void run() {
        super.run();
        long beginTime = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            //使用yield()方法放弃CPU时间
            this.yield();
            System.out.println(i++);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("执行完成,用时:" + (endTime - beginTime) + "毫秒!");
    }


    public static void main(String[] args) {
        Test01 thread = new Test01();
        thread.start();
    }
}

//打印结果

9984
9986
9988
9990
9992
9994
9996
9998
执行完成,用时:241毫秒!

事实证明,执行yield()方法把CPU时间给其他程序,会使此程序执行效率变慢。

原文地址:https://www.cnblogs.com/itiande/p/9519241.html