public class Demo {
public static void main(String[] args) throws IOException {
// =====================Thread多线程===================================
/**多线程单例模式
* 1、控制类的创建,不让其他类来继承对象,private
* 2、在本类中定义一个类对象 Singleton s
* 3、提供公共的访问方式。public static Singleton getInstance(){return s}
* 单例模式分为两种:饿汉模式、懒汉模式
* 区别:
* 1、饿汉式使空间换时间,懒汉式是时间换空间
* 2、在多线程访问时,饿汉式不会创建多个对象,而懒汉式会创建多个对象
*/
Singleton.print();
Singleton2.print();
/** Runtime类
* Runtime是一个单例类
*/
Runtime r = Runtime.getRuntime();
//r.exec("shutdown -s 300");//300秒后关机
//r.exec("shutdown -a");//取消关机
/** 两个线程之间通信:等待唤醒机制
* wait();线程等待
* notify();唤醒在此对象监视器上等待的单个线程
* notifyAll();唤醒在此对象监视器上等待的所有线程
* 在同步代码块中,用那个对象锁,就用那个对象调用wait方法
* sleep和wait的区别:
* 1、sleep方法必须传入参数,参数就是时间,时间到了自动醒来
* wait方法可以传入参数也可以不传参数,传入参数就是时间结束后开始等待,不传参数直接等待
* 2、sleep方法在同步函数或同步代码块中不释放锁
* wait方法在同步汉说或同步代码块中释放锁
*/
final Printer p = new Printer();
new Thread() {
public void run() {
while (true) {
try {
p.print1();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}.start();
new Thread() {
public void run() {
while (true) {
try {
p.print2();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}.start();
/**互斥锁(JDK1.5)
* 1、同步
* ReentrantLockl类的lock()和unlock()方法同步;替换synchronized
* 2、通信
* 使用ReentrantLock类的newCondition()方法可以获取Condition对象
* 需要等待的时候使用Condition的await()方法,唤醒的时候用Signal()方法
* 不同的线程使用不同的Condition,这样就能区分唤醒的时候找那个线程了
*
*/
}
}
/**
* 饿汉模式
*/
class Singleton{
//1、私有构造方法
private Singleton() {}
//2、创建本类对象
private static Singleton s = new Singleton();
//3、对外提供公共的访问方法
public static Singleton getInstance() {
return s;
}
public static void print() {
System.out.println("饿汉模式");
}
}
/**
* 懒汉模式
*/
class Singleton2{
//1私有构造函数
private Singleton2() {}
//2、声明一个类的引用
private static Singleton2 s2;
//3、对外提供公共的方法
public static Singleton2 getSingleton() {
if (s2 == null) {
s2 = new Singleton2();
}
return s2;
}
public static void print() {
System.err.println("懒汉模式");
}
}
class Printer{
private int flag = 1;
public void print1() throws InterruptedException {
synchronized (this) {
if (flag != 1) {
this.wait();
}
System.out.print("你");
System.out.print("好");
System.out.print("\r\n");
this.flag = 2;
this.notify();
}
}
public void print2() throws InterruptedException {
synchronized (this) {
if (flag != 2) {
this.wait();
}
System.out.print("世");
System.out.print("界");
System.out.print("\r\n");
this.flag = 1;
this.notify();
}
}
}