1、代码
- public class Test {
- public static void main(String[] args) {
- Data data = new Data();
- Add add = new Add(data);
- Dec dec = new Dec(data);
- for (int i = 0; i < 2; ++i) {
- new Thread(add, "线程A").start();
- new Thread(dec, "线程B").start();
- }
- }
- }
- class Data {
- private int j = 0;
- public synchronized void add(){
- System.out.println(Thread.currentThread().getName() + "对j加1,当前j=" + (++j));
- }
- public synchronized void dec(){
- System.out.println(Thread.currentThread().getName() + "对j减1,当前j=" + (--j));
- }
- }
- class Add implements Runnable{
- private Data data;
- Add(Data data){
- this.data= data;
- }
- public void run() {
- data.add();
- }
- }
- class Dec implements Runnable{
- private Data data;
- Dec(Data data){
- this.data= data;
- }
- public void run() {
- data.dec();
- }
- }
- 线程A对j加1,当前j=1
- 线程A对j加1,当前j=2
- 线程B对j减1,当前j=1
- 线程B对j减1,当前j=0
Java线程同步示例
本文通过一个Java示例展示了如何使用synchronized关键字实现线程间的同步操作。具体包括两个线程分别对共享变量进行增加和减少的过程,并观察运行结果。

被折叠的 条评论
为什么被折叠?



