zoukankan      html  css  js  c++  java
  • java 两个线程

    简介

    使用synchronized, 来实现两个线程的同步操作.

    参考链接

    https://www.cnblogs.com/leihuazhe/p/7898563.html

    TIPS

        唤醒一个在等待资源的线程.
        public final native void notify();
        阻塞资源, 等待被唤醒.
        public final void wait() throws InterruptedException {
            wait(0);
        }
    

    Synchronized 锁的对象是方法的调用者, 两个方法用的是同一个锁, 谁先拿到谁先执行

    code

    /**
     * Created by lee on 2021/6/21.
     */
    public class Add {
        public synchronized void  one() throws InterruptedException {
            boolean flag = true;
            while(flag) {
                for(int i = 1; i<=99; i+=2) {
                    System.out.println(Thread.currentThread().getName()+ " i " + i);
                    if(i == 99) {
                        flag = false;
                        this.notify();
                        break;
                    }
                    this.notify();
                    this.wait();
                }
            }
        }
        public synchronized void two() throws  InterruptedException {
            boolean flag = true;
            while(flag) {
                for(int i = 2; i<=100; i+=2) {
                    System.out.println(Thread.currentThread().getName()+ " i " + i);
                    if(i == 100) {
                        flag = false;
                        this.notify();
                        break;
                    }
                    this.notify();
                    this.wait();
                }
            }
        }
    
        public static void main(String[] args) {
            Add a = new Add();
    
            new Thread(()->{
                try {
                    a.one();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"A").start();
    
            new Thread(()->{
                try {
                    a.two();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"B").start();
        }
    }
    
    
    

    结果

    B i 98
    A i 99
    B i 100
    
    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    例5-6
    例5-5
    例5-4
    例4-5
    例4-4
    例4-3
    例4-2
    例3-11
    例3-10
    例3-9
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/14913613.html
Copyright © 2011-2022 走看看