首页 > 其他分享 >ThreadMBean

ThreadMBean

时间:2022-11-25 15:59:00浏览次数:50  
标签:int void System static ThreadMBean public out

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);
	}
}

  

 

标签:int,void,System,static,ThreadMBean,public,out
From: https://www.cnblogs.com/CAOXIAOYANG/p/16925394.html

相关文章