public class SingleTon1 {
private SingleTon1(){
}
private static SingleTon1 instance = null;
public static SingleTon1 getInstance(){
if(instance == null){
instance = new SingleTon1();
}
return instance;
}
}
package singleton;
public class SingleTon1 {
private SingleTon1(){
}
private static SingleTon1 instance = null;
//多线程问题解法一,但是效率不高!因为每次调用都会加锁!
public static synchronized SingleTon1 getInstance(){
if(instance == null){
instance = new SingleTon1();
}
return instance;
}
public void print(){
System.out.println("thread_id:"+Thread.currentThread().getId());
}
private static Object object = new Object();
//很巧妙的方法,只有在null的时候加锁,之后就不加啦
public static SingleTon1 getInstance2(){
if(instance == null){
synchronized (object){
instance = new SingleTon1();
}
}
return instance;
}
}
package singleton;
import java.util.concurrent.locks.ReentrantLock;
public class SingleTon2 {
private SingleTon2(){
}
private static ReentrantLock lock = new ReentrantLock();
private static SingleTon2 instance = null;
public void print(){
System.out.println("thread_id:"+Thread.currentThread().getId());
}
public static SingleTon2 getInstance2(){
if(instance == null){
lock.lock();
if(instance == null){ //注意这里还要判断下!!
instance = new SingleTon2();
}
lock.unlock();
}
return instance;
}
}
package singleton;
public class SingleTon3 {
public static void print(){
System.out.println("thread_id:"+Thread.currentThread().getId());
}
public static Nested getNested(){
return Nested.instance;
}
//这个是单例创建的类
static class Nested{
private Nested(){
}
static Nested instance = new Nested();
}
}
package singleton;
import singleton.SingleTon3.Nested;
public class Test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Nested singleton;
Myrunnable mm = new Myrunnable();
Myrunnable m1 = new Myrunnable();
Myrunnable2 m2 = new Myrunnable2();
new Thread(m1).start();
new Thread(m2).start();
if(m1.singleton == m2.singleton){ //是同一个
System.out.println("是同一个");
}else{
System.out.println("不是同一个");
}
}
}
class Myrunnable implements Runnable{
Nested singleton;
@Override
public void run() {
// TODO Auto-generated method stub
singleton = SingleTon3.getNested();
SingleTon3.print();
}
}
class Myrunnable2 implements Runnable{
Nested singleton;
@Override
public void run() {
// TODO Auto-generated method stub
singleton = SingleTon3.getNested();
SingleTon3.print();
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有