• 线程同步知识点


    从代码示例观察Thread相关的性质:

    1. wait和notify:

    /*
    wait:
    The current thread must own this object's monitor. 
    The thread releases ownership of this monitor and waits until another thread notifies threads
    waiting on this object's monitor to wake up either through a call to the notify method
    or the notifyAll method. The thread then waits
    until it can re-obtain ownership of the monitor and resumes execution.
    */ public class Test_Wait { public static void main(String[] args) { final Object obj = new Object(); class Waiter implements Runnable { @Override public void run() { synchronized(obj) { try { obj.wait(); //释放监视器锁,并等待 System.out.println("wake from wait"); } catch (InterruptedException e) { e.printStackTrace(); } } } } Thread waitThread = new Thread(new Waiter()); waitThread.start(); try { Thread.sleep(1000); //保证waitThread先执行 } catch (InterruptedException e) { e.printStackTrace(); } synchronized(obj) { obj.notifyAll(); //唤醒obj的等待线程 } } }

    2. join

    /*
    join: Waits for this thread to die. 
    */
    public class TestJoin {
        public static void main(String[] args) throws InterruptedException {
            Printer p1 = new Printer();
            p1.alphet = 'x';
            Printer p2 = new Printer();
            p2.alphet = 'y';
            
            p2.prevT = p1; //先执行p1,后p2。如果注释该行,则p1和p2顺序不定
            p1.start();
            p2.start();
        }
    }
    
    class Printer extends Thread {
        Thread prevT = null;
        char alphet = '';
        public void run() {
            if (null != prevT) {
                try {
                    prevT.join(); //类似插队,线程t插到当前线程前面,只有线程t死掉后,才执行当前线程
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(alphet);
        }
    }

    3. interrupt

    Thread.interrupt 方法只是置标志位 interrupt status 为 true

    如果线程的 interrupt status 为 true,则调用 sleep 会置 interrupt status 为 false,并且收到 InterruptedException,如果线程处于运行状态,则可以根据 interrupt status 来决定是否运行。

    /*
    interrupt:
    If this thread is blocked in an invocation of the wait(), wait(long), 
    or wait(long, int) methods of the Object class, or of the join(), join(long), 
    join(long, int), sleep(long), or sleep(long, int), methods of this class, 
    then its interrupt status will be cleared and it will receive an InterruptedException. 
    */
    public class TestInterrupt {
        public static void main(String[] args) throws IOException {
            SleepThread sleepThread = new SleepThread();
            sleepThread.start();
            //使sleep中的线程抛出InterruptedException
            sleepThread.interrupt();
            
            WaitThread waitThread = new WaitThread();
            waitThread.start();
            //使wait中的线程抛出InterruptedException
            waitThread.interrupt();
        }
    }
    
    class SleepThread extends Thread {
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }
    }
    
    class WaitThread extends Thread {
        public synchronized void run() {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

     4. Condition的await和signal()

    public class Condition_Test {
        public static void main(String[] args) {
            final ReentrantLock lock = new ReentrantLock();
            final Condition cond = lock.newCondition();
            //wait线程
            class Waiter implements Runnable {
                @Override
                public void run() {
                    lock.lock();
                    try {
                        cond.await();
                        System.out.println("wake from await");
                    } catch(InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                    
                }
            }
            
            new Thread(new Waiter()).start();
            
            try {
                Thread.sleep(1000); // 保证wait线程先执行
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            //主线程唤醒等待线程
            lock.lock();
            cond.signal();
            lock.unlock();
        }
    }

    wait和notify是Object类中的方法,在同步代码块中,Object对象既是锁,又充当阻塞的条件。而ReentrantLock和Condition做了一个切分。

  • 相关阅读:
    Many Equal Substrings CF
    Seek the Name, Seek the Fame POJ
    人人都是好朋友(离散化 + 并查集)
    建设道路
    day_30
    day_29作业
    day_29
    day_28
    day_27
    day_26作业
  • 原文地址:https://www.cnblogs.com/allenwas3/p/8301294.html
Copyright © 2020-2023  润新知