ThreadMBean

package com.google.thread3;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

public class ThreadDemo {
	public static void main(String[] args) {
		ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
		ThreadInfo[] dumpAllThreads = threadMXBean.dumpAllThreads(false, false);
		for (int i = 0; i < dumpAllThreads.length; i++) {
			ThreadInfo threadInfo = dumpAllThreads[i];
			System.out.println(threadInfo.getThreadId()+threadInfo.getThreadName());
		}
	}
}

ABA问题

package com.google;

import java.util.concurrent.atomic.AtomicInteger;

//volatile 不保证原子性 
//解决volatile的原子性问题(synchronized)(AtomicInteger--->CAS) 
class MyData2 {
	AtomicInteger number = new AtomicInteger();
	public  void addPlus() {
		number.addAndGet(1);
	}
}

public class Demo2 {
	public static void main(String[] args) {
		MyData2 myData2 = new MyData2();
		for (int i = 1; i <= 20; i++) {
			new Thread(() -> {
				for (int j = 1; j <= 1000; j++) {
					myData2.addPlus();
				}
			}, "AAA").start();
		}
		while (Thread.activeCount() > 2) {
			Thread.yield();
		}
		System.out.println(myData2.number);
	}
}

指令重排序

package com.google;
//指令重排序
public class Demo3 {
	public static void main(String[] args) {
		mySort();
	}
	public static void mySort(){
		int x = 11;
		int y = 12;
		x = x + 5;
		y = x * x;
		System.out.println(x);
		System.out.println(y);
	}
}

  

 

posted @ 2022-11-25 15:45  Sunray0330  阅读(49)  评论(0编辑  收藏  举报