多线程-线程池
代码如下:
public class Demo13 {
public static void main(String[] args) {
//1.创建服务,创建线程池,线程池大小10
ExecutorService service = Executors.newFixedThreadPool(10);
MyThread myThread = new MyThread();
//执行
service.execute(myThread);
service.execute(myThread);
service.execute(myThread);
//2.关闭连接
service.shutdown();
/*MyThread ticket = new MyThread();
new Thread(ticket,"小明").start();
new Thread(ticket,"老师").start();
new Thread(ticket,"黄牛").start();*/
}
}
class MyThread implements Runnable{
private int ticketNums = 10;
private boolean flag = true;//外部停止方式
@Override
public void run() {
while (flag){
buy();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void buy(){
if (ticketNums <= 0){
flag = false;
return;
}else {
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"张票");
}
}
}
会报空指针异常。
解决方法是:
新建一个获取bean的工具类
package com.example.test.thread;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
/**
* 上下文对象实例
*/
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 获取applicationContext
*
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 通过name获取 Bean.
*
* @param name
* @return
*/
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
/**
* 通过class获取Bean.
*
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
/**
* 通过name,以及Clazz返回指定的Bean
*
* @param name
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
使用:创建一个无参的构造方法,在里面调用工具类的getBean()方法即可。
private UserinfoService userinfoService;
public Running() {
this.userinfoService = ApplicationContextProvider.getBean(UserinfoService.class);
}