线程同步类,定义AtomicInteger原子变量,实现线程同步- import java.util.concurrent.atomic.AtomicInteger;
- public class AtomicIntegerDemo implements Runnable {
-
- private AtomicInteger number = new AtomicInteger(0);// 创建一个AtomicInteger类型变量进行测试
-
- @Override
- public void run() {
- for (int i = 0; i < 5; i++) {
- try {
- Thread.sleep(100);// 线程休眠0.1秒增加出错几率
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- // 输出当前线程的名称和number的值,每次循环之后number的值都会加一
- System.out.println(Thread.currentThread().getName() + ": "
- + number.getAndIncrement());
- }
- }
-
- public static void main(String[] args) {
- AtomicIntegerDemo run = new AtomicIntegerDemo();// 获得AtomicIntegerDemo对象
- Thread thread1 = new Thread(run);// 创建线程1
- Thread thread2 = new Thread(run);// 创建线程2
- thread1.start();// 运行线程1
- thread2.start();// 运行线程2
- }
- }
复制代码 运行结果:
Thread-0: 0
Thread-1: 1
Thread-0: 2
Thread-1: 3
Thread-1: 4
Thread-0: 5
Thread-1: 6
Thread-0: 7
Thread-1: 8
Thread-0: 9
|