标签:memory 同步机制 extend public 解锁 ati ret 自己 mem
class MyThreadEx extends Thread{
private String title;
MyThreadEx(String title){
this.title = title;
}
@Override
public void run() {
for (int i = 0;i < 10;i++){
System.out.println(currentThread().getName()+"--"+title+":"+i);
}
}
}
【调用】
MyThreadEx thread = new MyThreadEx("A");
thread.start();
class MyThread implements Runnable{
private int i = 0;
@Override
public void run() {
for (;i < 10;i++)
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
【调用】
MyThread runthread = new MyThread();
new Thread(runthread,"A").start();
【实现】
class MyCallThread implements Callable{
private int i = 0;
@Override
public Object call() throws Exception {
for (; i < 10; i++){
System.out.println(Thread.currentThread() + "-callable:"+ i);
}
return "callable";
}
}
【调用】
FutureTask<String> task = new FutureTask<>(new MyCallThread());
new Thread(task).start();
System.out.println(task.get());
atomic:原子 ,AtomicInteger:原子引用
1.volatile java虚拟机提供的轻量级的同步机制
特性:
(1)保证可见性
(2)不保证原子性
(3)禁止指令重排
public class Singleton{
private static volatitle Singleton instance = null; //volatitle轻量级线程同步机制
private Singleton(){
}
public static Singleton getInstance(){ //方法加synchronized,效率低
if(instance == null){
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
}
}
2.JMM:(java memory model)java内存模型,抽象概念,并不真实存在
JMM 同步规定:
(1)线程解锁之前,必须把共享的值刷新回主内存
(2)线程加锁前,必须读取主内存最新的值到自己的工作内存
(3)加锁解锁是同一把锁
标签:memory 同步机制 extend public 解锁 ati ret 自己 mem
原文地址:https://www.cnblogs.com/monkay/p/11376623.html