多线程 创建子父线程 保证一件事 子线程执行三次后 父线程执行5次 循环10次

package Thread;

/**
 * 创建子父线程 保证一件事 子线程执行三次后 父线程执行5次 循环10次
 * 父线程main线程则为Console台项目的主线程
 * 在main线程中调用了start线程则为子线程
 * 
 */
public class FatherAndSonTest {
    public static void main(String[] args) {
        final FatherAndSon  fs = new FatherAndSon();
        new Thread(new Runnable(){
            //JVM 叫本地方法栈
            @Override
            public void run() {
       //子线程的线程体
                for (int i = 0; i < 10; i++) 
                    fs.sub();
                
            }
        
            
        }).start();
        //父线程的线程体
        for (int i = 0; i < 10; i++) {
            fs.father();
        }
    }

}
package Thread;

public class FatherAndSon {
    /**
     * 匿名内部类:并不是说接口一定不可用被new
     * 为何这两个方法都必须是同步方法 这两个方法所使用的同步锁都为this?
     * 谁又是this: 谁调用father|son 谁就是this
     * this 子线程--->父--->子--->父
     *     子 父 
     *     子 子
     *     父 子
     *     父 父
     */
    boolean flag = true;//开关 为true时 子线程执行 为false时 父线程执行 
    // 什么时候回释放锁? wait|方法执行结束
    public synchronized void father(){
        if(flag){
            //理当父线程不执行 wait():如果在一个线程 中调用了obj.wait():
            //自己本身进入阻塞状态并释放对锁的占有(立即释放);
            // notify():唤醒线程(唤醒的是等待obj锁的线程)阻塞队列---->Object 方法
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for (int i = 0; i < 5; i++) {
            System.out.println("父线程第"+(i+1)+"次执行");
        }
        flag=true;
        this.notify();
    }
    //this FatherAndSon son = new FatherAndSon();对象是单例的
    public synchronized void sub(){
        if(!flag){
            //理当父线程不执行 wait():如果在一个线程 中调用了obj.wait():自己本身进入阻塞状态
            //并释放对锁的占有(立即释放)
            //notify():唤醒线程(唤醒的是等待obj锁的线程)阻塞队列--->Object的方法
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for (int i = 0; i < 3; i++) {
            System.out.println("子线程第"+(i+1)+"次执行");
        }
        flag= false;
        this.notify();
    }
}

猜你喜欢

转载自www.cnblogs.com/ls1783047205/p/9751039.html