package com.itheim.threadAtom;
public class MyAtomThread implements Runnable{
private int count=0;//送冰激凌的数量
private Object lock=new Object();
@Override
public void run() {
for (int i = 0; i < 100; i++) {
synchronized (lock) {
count++;
System.out.println("已经送了"+count+"个冰激凌");
}
}
}
}
package com.itheim.threadAtom;
public class AtomDemo {
public static void main(String[] args) {
MyAtomThread atom=new MyAtomThread();
for (int i = 0; i < 100; i++) {
new Thread(atom).start();
}
}
}
此代码示例展示了如何在Java中使用synchronized关键字实现线程同步,确保在多线程环境下正确递增送冰激凌的数量。在main方法中创建了100个线程,每个线程都会递增count变量,避免数据竞争问题。
1732

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



