Singleton:---------
package cn.tools;
public class Singleton {
//饿汉模式(变种)
/*private static Singleton singleton;
static{
singleton = new Singleton();
System.out.println("static ===== "+singleton.toString());
}
private Singleton(){}
public static Singleton getInstance(){
System.out.println("getInstance===========");
return singleton;
}
public static void test(){
System.out.println("test======== " + singleton.toString());
}*/
//双重校验锁
/*private static Singleton singleton ;
private Singleton(){}
public static Singleton getInstance(String threadNo){
//T1 T2 T3
//T4
if(singleton == null){
//T1 T2 T3
System.out.println("singleton 1 ================== threadNo:"+threadNo);
synchronized (Singleton.class) {
//T2 T1 T3
System.out.println("singleton 2 ================== threadNo:"+threadNo);
if(singleton == null){
//T2
System.out.println("singleton 3 ============== threadNo:"+threadNo);
singleton = new Singleton();
}
}
}
return singleton;
}*/
//静态内部类 lazy loading
private static Singleton singleton;
private Singleton(){}
private static class SingletonHelper{
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance(){
return SingletonHelper.INSTANCE;
}
public static void test(){
System.out.println("test===" + singleton.toString());
}
}
TestSingleton:---------
package cn.tools;
public class TestSingleton {
public static void main(String[] args) {
System.out.println("Singleton.getInstance() === " +
Singleton.getInstance().toString());
//Singleton.test();
}
}
ThreadDemo:---------
package cn.tools;
public class ThreadDemo extends Thread {
private String threadNo;
public ThreadDemo(String _threadNo){
threadNo = _threadNo;
}
@Override
public void run() {//线程开始执行
// TODO Auto-generated method stub
super.run();
System.out.println("run ================ threadNo:"+threadNo);
//Singleton.getInstance(threadNo);
}
public String getThreadNo() {
return threadNo;
}
public void setThreadNo(String threadNo) {
this.threadNo = threadNo;
}
}
TestThreadDemo:---------
package cn.tools;
public class TestThreadDemo {
public static void main(String[] args) {
//for:主线程(获取cpu资源之后,瞬间生成n个子线程,n个并发)
for(int i = 0; i < 4; i++){
//new 开辟子线程 start:调用run,运行子线程
new ThreadDemo("thread"+i).start();
if(i == 1){
try {
Thread.sleep(1000);
System.out.println("sleep=====================");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}