Java同步机制:synchronized,wait,notify

本文通过一个具体的Java程序示例介绍了线程同步的基本原理,利用生产者消费者模式展示了如何使用synchronized关键字来实现线程间的同步操作,确保数据的一致性和线程的安全访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class ThreadSyn {  
      
    public static void main(String[] args) {  
        new ThreadSyn();  
    }  
  
    public ThreadSyn() {  
        Queue queue = new Queue();  
  
        Producter p = new Producter(queue);  
        Consumer c = new Consumer(queue);  
  
        p.start();  
        c.start();  
    }  
  
      
    // Queue模拟Java线程同步中的生产者消费者仓库、队列。  
    private class Queue {  
        int value; // 为了使例子简单,value即为假设长度为1的仓库、队列  
        boolean full = false;  
  
        public synchronized void put(int i) {  
            if (!full) {  
                value = i;  
                full = true;  
  
                notify();  
            }  
  
            try {  
                wait();  
            } catch (InterruptedException e) {  
                // e.printStackTrace();  
            }  
        }  
  
        public synchronized int get() {  
            if (!full)  
                try {  
                    wait();  
                } catch (InterruptedException e) {  
                    // e.printStackTrace();  
                }  
  
            full = false;  
  
            notify();  
  
            return value;  
        }  
    }  
  
      
    // Java线程同步模型-生产者  
    private class Producter extends Thread {  
        private Queue q;  
  
        public Producter(Queue q) {  
            this.q = q;  
        }  
  
        public void run() {  
            for (int i = 0; i < 20; i++) {  
                System.out.println("生产了:" + i);  
                q.put(i);  
            }  
        }  
    }  
  
    // Java线程同步模型-消费者  
    private class Consumer extends Thread {  
        private Queue q;  
  
        public Consumer(Queue q) {  
            this.q = q;  
        }  
  
        public void run() {  
            while (true) {  
                System.out.println("消费了:" + q.get());  
            }  
        }  
    }  
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值