首页 🔴 Java,📝 算法学习

1. synchronized 同步方式

public class Main {
    public static void main(String[] args) {
        Solve solve = new Solve();
        new Thread(()->{
            solve.print(1);
        }, "线程A").start();

        new Thread(()->{
            solve.print(0);
        }, "线程B").start();
    }
}

class Solve {
    private int number = 0;
    public synchronized void print(int op) {
        while (number < 100){
            while (op == (number & 1)) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + "打印了: " + number++);
            notifyAll();
        }
    }
}

控制台输出
自然数1.png


2. lock 锁方式

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    public static void main(String[] args) {
        Solve solve = new Solve();
        new Thread(()->{
            solve.print(1);
        }, "线程A").start();

        new Thread(()->{
            solve.print(0);
        }, "线程B").start();
    }
}

class Solve {
    private int number = 100;
    private Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    public void print(int op) {
        while (number > 0){
            lock.lock();
            try {
                while (op == (number & 1)) {
                    condition.await();
                }
                System.out.println(Thread.currentThread().getName() + "打印了: " + number--);
                condition.signalAll();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}

控制台输出
自然数2.png




文章评论