java 多线程 sleep 和wait

一 简介

sleep方法是Thread 的静态方法,所有可以调用此方法。Thread类,子类,还有实例化对象(和类调用一样)

wait方法是object的成员方法,作用是当前线程挂到等待队列上去。调用者锁池对象。。

       执行sleep,放弃CPU资源,但是不会放弃已经获得的锁

       执行wait ,放弃CPU资源,同时放弃锁资源。如果不加限制,还需要其他线程手动notify

锁的理解:就是一个对象,比如同步方法包含在Main类中,如果此方法是静态方法,锁就是Main.class

                  如果是非静态方法,就是Main实例对象.这是操作系统中 管程的体现,即对临界资源的访问,交由一个对象管理(这个对象就是观念上的锁)

二 demo

sleep的测试,结果显示,一个线程抢到资源后 经过10s 下一个线程才能得到资源,即sleep期间不释放锁

public class Test1 {
    static class MyThread extends  Thread{
        @Override
        public void run() {
            try {
                get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread thread=null;
        thread.sleep(100); //空对象调用 也不会报错  因为此方法是个类方法。
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        t1.start();
        t2.start();



    }

    public static synchronized void get() throws InterruptedException {
        System.out.println("线程"+Thread.currentThread().getName());
             Thread.sleep(10000);

    }
}

  wait的例子,首先如果方法不上锁,或者不在同步方法内调用此方法,都会抛出异常。同时 还是上面的抢资源

public class Test1 {
    static class MyThread extends  Thread{
        @Override
        public void run() {
            try {
                get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread thread=null;
        thread.sleep(100); //空对象调用 也不会报错  因为此方法是个类方法。
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        t1.start();
        t2.start();
            Test1.class.wait();  //抛出异常


    }

    public static synchronized void get() throws InterruptedException {
        System.out.println("线程"+Thread.currentThread().getName());
        Thread.sleep(10000);
        // Test1.class.wait(10000);   效果:线程秒切换  10s后  程序结束

    }
}

  

猜你喜欢

转载自www.cnblogs.com/caijiwdq/p/11164560.html