多线程知识点synchronized wait join yield

package com.hencoder.a17_thread_interaction;

/**
 *  读写锁。
 *     ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
 *     Lock readLock = lock.readLock();
 *     Lock writeLock = lock.writeLock();
 *
 */
public class WaitDemo implements TestDemo {
    private String sharedString;

    private int x=0;
    private int y=0;

    /**
     * synchronized 关键字是锁定当前的对象。
     * 被synchronized包括的代码块将会是一个原子性的操作,中间不会被打断
     */
    public synchronized void add(){
        //x++ 在cpu中是分为以下两个步骤来执行的
        //int tmep = x + 1;
        //x = temp;
        x++;
        y++;
    }

    public void sub(){
        synchronized (this){//这个 等价于 直接在方法上面加synchronized 关键字
            x--;
            y--;
        }
    }


    private synchronized void initString() {
        sharedString = "rengwuxian";
        notifyAll();//必须写在synchronized方法里
    }

    private synchronized void printString() {
        //wait()方法 会暂时丢掉synchronized锁。直到InterruptedException或者 notify
        while (sharedString == null) {//要用while因为 Thread.interrupted()也会唤醒wait();
            try {
                wait();//必须写在synchronized方法里,因为wait要释放锁
            } catch (InterruptedException e) {//如果线程被调用了Thread.interrupted()方法 则会抛出这个异常
                e.printStackTrace();
            }
        }
        System.out.println("String: " + sharedString);
    }

    @Override
    public void runTest() {
        final Thread thread1 = new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                printString();
            }
        };
        thread1.start();
        Thread thread2 = new Thread() {
            @Override
            public void run() {

                try {
                    thread1.join();//join方法会等待thread1运行完毕,才继续执行下面的代码。
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                Thread.yield();//暂时让出cpu,执行其他任务
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                initString();
            }
        };
        thread2.start();
    }
}

你可能感兴趣的:(多线程知识点synchronized wait join yield)