懒汉式线程安全,线程通信的常用方法,新增创建线程的方式
1.单例模式中懒汉式线程安全的写法
class Bank{
private Bank(){}
private static Bank instance;
//效率稍差
/*public synchronized static Bank getBankInstance(){
if (instance == null){
instance = new Bank();
}
return instance;
}*/
//效率较高
public static Bank getBankInstance() {
if (instance == null){
synchronized (Bank.class){
if (instance == null) {
instance = new Bank();
}
}
}
return instance;
}
}
2.线程通信的常用方法
1)wait():使线程进入阻塞状态,会释放同步监视器
2)notify():唤醒一个线程,如果有多个线程,则会唤醒优先级较高的线程
3)notifyAll():唤醒所有线程
3.sleep()与wait()的相同点与不同点
相同点:sleep与wait都会使线程进入阻塞状态
不同点:1)sleep不会施放同步监视器,wait会施放同步监视器
2)sleep在任何需要的地方都可以调用,wait只能在同步代码块与同步方法中调用,调用的对象必须是同步监视器
3)sleep是属于Thread类,wait是属于Object类
4.新增线程的创建方式(JDK5.0新增)
1)实现callable接口,重写call()方法
public class ThreadTest04 implements Callable {//1.实现Callable接口
@Override
public Object call() throws Exception {//2.重写call方法,可以有返回值,可以throws异常
int sum = 0;
for (int i = 1; i <= 100 ; i++) {
if (i%2 ==0){
System.out.println(i);
sum += i;
}
}
return sum;
}
public static void main(String[] args) {
ThreadTest04 test04 = new ThreadTest04();
FutureTask task = new FutureTask(test04);
Thread thread = new Thread(task);
thread.start();
try {
int sum = (int) task.get();//获取futuretask构造器中的参数重写call方法的返回值
System.out.println("总和为:" + sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
2)使用线程池创建线程
public class ThreadPool {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(new Thread1());
executorService.submit(new Thread2());
executorService.shutdown();
FutureTask futureTask = new FutureTask(new Thread2());
try {
Integer sum = futureTask.get();
System.out.println("总和为:" + sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
class Thread1 implements Runnable {
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
class Thread2 implements Callable {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i < 100; i++) {
if (i % 2 != 0) {
sum += i;
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
return sum;
}
}