Java笔试面试题整理第六波(修正版)
转载至:http://blog.csdn.net/shakespeare001/article/details/51330745
作者:山代王(开心阳)
本系列整理Java相关的笔试面试知识点,其他几篇文章如下:
1、线程池ThreadPool相关
- public static ExecutorService newFixedThreadPool(int nThreads) {
- return new ThreadPoolExecutor(nThreads, nThreads,
- 0L, TimeUnit.MILLISECONDS,
- new LinkedBlockingQueue<Runnable>());
- }

public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
- public ThreadPoolExecutor(int corePoolSize,
- int maximumPoolSize,
- long keepAliveTime,
- TimeUnit unit,
- BlockingQueue<Runnable> workQueue,
- ThreadFactory threadFactory,
- RejectedExecutionHandler handler)

public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
- ExecutorService threadpool= Executors.newFixedThreadPool(10);
- threadpool.execute(new Runnable(){…});

ExecutorService threadpool= Executors.newFixedThreadPool(10);
threadpool.execute(new Runnable(){...});
这种方式提交没有返回值,也就不能判断任务是否被线程池执行成功。
- Future<?> future = threadpool.submit(new Runnable(){…});
- try {
- Object res = future.get();
- } catch (InterruptedException e) {
- // 处理中断异常
- e.printStackTrace();
- } catch (ExecutionException e) {
- // 处理无法执行任务异常
- e.printStackTrace();
- }finally{
- // 关闭线程池
- executor.shutdown();
- }

Future<?> future = threadpool.submit(new Runnable(){...});
try {
Object res = future.get();
} catch (InterruptedException e) {
// 处理中断异常
e.printStackTrace();
} catch (ExecutionException e) {
// 处理无法执行任务异常
e.printStackTrace();
}finally{
// 关闭线程池
executor.shutdown();
}

- public class BankCount {
- public synchronized void addMoney(int money){//存钱
- System.out.println(Thread.currentThread().getName() + ”>存入:” + money);
- }
- public synchronized void getMoney(int money){//取钱
- System.out.println(Thread.currentThread().getName() + ”>取钱:” + money);
- }
- }

public class BankCount {
public synchronized void addMoney(int money){//存钱
System.out.println(Thread.currentThread().getName() + ">存入:" + money);
}
public synchronized void getMoney(int money){//取钱
System.out.println(Thread.currentThread().getName() + ">取钱:" + money);
}
}
- public class BankTest {
- public static void main(String[] args) {
- final BankCount bankCount = new BankCount();
- ExecutorService executor = Executors.newFixedThreadPool(10);
- executor.execute(new Runnable() {//存钱线程
- @Override
- public void run() {
- int i = 5;
- while(i– > 0){
- bankCount.addMoney(200);
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- });
- Future<?> future = executor.submit(new Runnable() {//取钱线程
- @Override
- public void run() {
- int i = 5;
- while(i– > 0){
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- bankCount.getMoney(200);
- }
- }
- });
- try {
- Object res = future.get();
- System.out.println(res);
- } catch (InterruptedException e) {
- // 处理中断异常
- e.printStackTrace();
- } catch (ExecutionException e) {
- // 处理无法执行任务异常
- e.printStackTrace();
- }finally{
- // 关闭线程池
- executor.shutdown();
- }
- }
- }

public class BankTest {
public static void main(String[] args) {
final BankCount bankCount = new BankCount();
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.execute(new Runnable() {//存钱线程
@Override
public void run() {
int i = 5;
while(i-- > 0){
bankCount.addMoney(200);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Future<?> future = executor.submit(new Runnable() {//取钱线程
@Override
public void run() {
int i = 5;
while(i-- > 0){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
bankCount.getMoney(200);
}
}
});
try {
Object res = future.get();
System.out.println(res);
} catch (InterruptedException e) {
// 处理中断异常
e.printStackTrace();
} catch (ExecutionException e) {
// 处理无法执行任务异常
e.printStackTrace();
}finally{
// 关闭线程池
executor.shutdown();
}
}
}
2、生产者和消费者模型
- /**
- * 仓库
- */
- public class Storage {
- private static final int MAX_SIZE = 100;//仓库的最大容量
- private List<Object> data = new ArrayList<Object>();//存储载体
- /**
- * 生产操作
- */
- public synchronized void produce(int num){
- if(data.size() + num > MAX_SIZE){//如果生产这些产品将超出仓库的最大容量,则生产操作阻塞
- System.out.println(”生产操作–>数量:” + num + “,超出仓库容量,生产阻塞!——库存:” + data.size());
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- //到这里,表示可以正常生产产品
- for(int i = 0; i < num; i++){//生产num个产品
- data.add(new Object());
- }
- System.out.println(”生产操作–>数量:” + num + “,成功入库~——库存:” + data.size());
- //生产完产品后,唤醒其他等待消费的线程
- notify();
- }
- /**
- * 消费操作
- */
- public synchronized void consume(int num){
- if(data.size() - num < 0){//如果产品数量不足
- System.out.println(”消费操作–>数量:” + num + “,库存不足,消费阻塞!——库存:” + data.size());
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- //到这里,表示可以正常消费
- for(int i = 0; i < num; i++){//消费num个产品
- data.remove(0);
- }
- System.out.println(”消费操作–>数量:” + num + “,消费成功~——库存:” + data.size());
- //消费完产品后,唤醒其他等待生产的线程
- notify();
- }
- }

/**
* 仓库
*/
public class Storage {
private static final int MAX_SIZE = 100;//仓库的最大容量
private List<Object> data = new ArrayList<Object>();//存储载体
/**
* 生产操作
*/
public synchronized void produce(int num){
if(data.size() + num > MAX_SIZE){//如果生产这些产品将超出仓库的最大容量,则生产操作阻塞
System.out.println("生产操作-->数量:" + num + ",超出仓库容量,生产阻塞!------库存:" + data.size());
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//到这里,表示可以正常生产产品
for(int i = 0; i < num; i++){//生产num个产品
data.add(new Object());
}
System.out.println("生产操作-->数量:" + num + ",成功入库~------库存:" + data.size());
//生产完产品后,唤醒其他等待消费的线程
notify();
} /**
* 消费操作
*/
public synchronized void consume(int num){
if(data.size() - num < 0){//如果产品数量不足
System.out.println("消费操作-->数量:" + num + ",库存不足,消费阻塞!------库存:" + data.size());
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//到这里,表示可以正常消费
for(int i = 0; i < num; i++){//消费num个产品
data.remove(0);
}
System.out.println("消费操作-->数量:" + num + ",消费成功~------库存:" + data.size());
//消费完产品后,唤醒其他等待生产的线程
notify();
} }
- public class Producer implements Runnable{
- private Storage storage;
- private int num;//每次生产多少个
- public Producer(Storage sto,int num){
- storage = sto;
- this.num = num;
- }
- @Override
- public void run() {
- storage.produce(num);
- }
- }

public class Producer implements Runnable{
private Storage storage;
private int num;//每次生产多少个
public Producer(Storage sto,int num){
storage = sto;
this.num = num;
}
@Override
public void run() {
storage.produce(num);
}
}
- public class Consumer implements Runnable{
- private Storage storage;
- private int num;//每次消费多少个
- public Consumer(Storage sto,int num){
- storage = sto;
- this.num = num;
- }
- @Override
- public void run() {
- storage.consume(num);
- }
- }

public class Consumer implements Runnable{
private Storage storage;
private int num;//每次消费多少个
public Consumer(Storage sto,int num){
storage = sto;
this.num = num;
}
@Override
public void run() {
storage.consume(num);
}
}
- public class StorageTest {
- public static void main(String[] args) {
- Storage storage = new Storage();
- ExecutorService taskSubmit = Executors.newFixedThreadPool(10); //来使用使用上一节我们总结的线程池知识
- //给定4个消费者
- taskSubmit.submit(new Consumer(storage, 30));
- taskSubmit.submit(new Consumer(storage, 10));
- taskSubmit.submit(new Consumer(storage, 20));
- //给定6个生产者
- taskSubmit.submit(new Producer(storage, 70));
- taskSubmit.submit(new Producer(storage, 10));
- taskSubmit.submit(new Producer(storage, 20));
- taskSubmit.submit(new Producer(storage, 10));
- taskSubmit.submit(new Producer(storage, 10));
- taskSubmit.submit(new Producer(storage, 10));
- taskSubmit.shutdown();
- }
- }

public class StorageTest {
public static void main(String[] args) {
Storage storage = new Storage();
ExecutorService taskSubmit = Executors.newFixedThreadPool(10); //来使用使用上一节我们总结的线程池知识
//给定4个消费者
taskSubmit.submit(new Consumer(storage, 30));
taskSubmit.submit(new Consumer(storage, 10));
taskSubmit.submit(new Consumer(storage, 20));
//给定6个生产者
taskSubmit.submit(new Producer(storage, 70));
taskSubmit.submit(new Producer(storage, 10));
taskSubmit.submit(new Producer(storage, 20));
taskSubmit.submit(new Producer(storage, 10));
taskSubmit.submit(new Producer(storage, 10));
taskSubmit.submit(new Producer(storage, 10));
taskSubmit.shutdown();
}
}
- XmppManager xmppManager = notificationService.getXmppManager();
- if(xmppManager != null){
- if(!xmppManager.isAuthenticated()){
- try {
- synchronized (xmppManager) {//等待客户端连接认证成功
- Log.d(LOGTAG, ”wait for authenticated…”);
- xmppManager.wait();
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }

XmppManager xmppManager = notificationService.getXmppManager();
if(xmppManager != null){
if(!xmppManager.isAuthenticated()){
try {
synchronized (xmppManager) {//等待客户端连接认证成功
Log.d(LOGTAG, "wait for authenticated...");
xmppManager.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
- /**
- * 仓库
- */
- public class Storage {
- private static final int MAX_SIZE = 100;//仓库的最大容量
- private List<Object> data = new ArrayList<Object>();//存储载体
- private Lock lock = new ReentrantLock();//可重入锁
- private Condition full = lock.newCondition();//仓库满的条件变量
- private Condition empty = lock.newCondition();//仓库空时的条件变量
- /**
- * 生产操作
- */
- public void produce(int num){
- lock.lock(); //加锁
- if(data.size() + num > MAX_SIZE){//如果生产这些产品将超出仓库的最大容量,则生产操作阻塞
- System.out.println(”生产操作–>数量:” + num + “,超出仓库容量,生产阻塞!——库存:” + data.size());
- try {
- full.await(); //阻塞
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- //到这里,表示可以正常生产产品
- for(int i = 0; i < num; i++){//生产num个产品
- data.add(new Object());
- }
- System.out.println(”生产操作–>数量:” + num + “,成功入库~——库存:” + data.size());
- //生产完产品后,唤醒其他等待消费的线程
- empty.signalAll();
- lock.unlock(); //释放锁
- }
- /**
- * 消费操作
- */
- public void consume(int num){
- lock.lock(); //加锁
- if(data.size() - num < 0){//如果产品数量不足
- System.out.println(”消费操作–>数量:” + num + “,库存不足,消费阻塞!——库存:” + data.size());
- try {
- empty.await(); //阻塞
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- //到这里,表示可以正常消费
- for(int i = 0; i < num; i++){//消费num个产品
- data.remove(0);
- }
- System.out.println(”消费操作–>数量:” + num + “,消费成功~——库存:” + data.size());
- //消费完产品后,唤醒其他等待生产的线程
- full.signalAll();
- lock.unlock(); //释放锁
- }
- }

/**
* 仓库
*/
public class Storage {
private static final int MAX_SIZE = 100;//仓库的最大容量
private List<Object> data = new ArrayList<Object>();//存储载体 private Lock lock = new ReentrantLock();//可重入锁
private Condition full = lock.newCondition();//仓库满的条件变量
private Condition empty = lock.newCondition();//仓库空时的条件变量 /**
* 生产操作
*/
public void produce(int num){
lock.lock(); //加锁
if(data.size() + num > MAX_SIZE){//如果生产这些产品将超出仓库的最大容量,则生产操作阻塞
System.out.println("生产操作-->数量:" + num + ",超出仓库容量,生产阻塞!------库存:" + data.size());
try {
full.await(); //阻塞
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//到这里,表示可以正常生产产品
for(int i = 0; i < num; i++){//生产num个产品
data.add(new Object());
}
System.out.println("生产操作-->数量:" + num + ",成功入库~------库存:" + data.size());
//生产完产品后,唤醒其他等待消费的线程
empty.signalAll(); lock.unlock(); //释放锁
} /**
* 消费操作
*/
public void consume(int num){
lock.lock(); //加锁
if(data.size() - num < 0){//如果产品数量不足
System.out.println("消费操作-->数量:" + num + ",库存不足,消费阻塞!------库存:" + data.size());
try {
empty.await(); //阻塞
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//到这里,表示可以正常消费
for(int i = 0; i < num; i++){//消费num个产品
data.remove(0);
}
System.out.println("消费操作-->数量:" + num + ",消费成功~------库存:" + data.size());
//消费完产品后,唤醒其他等待生产的线程
full.signalAll(); lock.unlock(); //释放锁
}
}
- public class Storage {
- private static final int MAX_SIZE = 100;//仓库的最大容量
- private BlockingQueue<Object> data = new LinkedBlockingQueue<Object>(MAX_SIZE); //使用阻塞队列作为存储载体
- /**
- * 生产操作
- */
- public void produce(int num){
- if(data.size() == MAX_SIZE){//如果仓库已达最大容量
- System.out.println(”生产操作–>仓库已达最大容量!”);
- }
- //到这里,表示可以正常生产产品
- for(int i = 0; i < num; i++){//生产num个产品
- try {
- data.put(new Object()); //put内部自动实现了判断,超过最大容量自动阻塞
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.println(”生产操作–>数量:” + num + “,成功入库~——库存:” + data.size());
- }
- /**
- * 消费操作
- */
- public void consume(int num){
- if(data.size() == 0){//如果产品数量不足
- System.out.println(”消费操作–库存不足!”);
- }
- //到这里,表示可以正常消费
- for(int i = 0; i < num; i++){//消费num个产品
- try {
- data.take(); //take内部自动判断,消耗后库存是否充足,不足自我阻塞
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.println(”消费操作–>数量:” + num + “,消费成功~——库存:” + data.size());
- }
- }

public class Storage {
private static final int MAX_SIZE = 100;//仓库的最大容量
private BlockingQueue<Object> data = new LinkedBlockingQueue<Object>(MAX_SIZE); //使用阻塞队列作为存储载体
/**
* 生产操作
*/
public void produce(int num){
if(data.size() == MAX_SIZE){//如果仓库已达最大容量
System.out.println("生产操作-->仓库已达最大容量!");
}
//到这里,表示可以正常生产产品
for(int i = 0; i < num; i++){//生产num个产品
try {
data.put(new Object()); //put内部自动实现了判断,超过最大容量自动阻塞
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("生产操作-->数量:" + num + ",成功入库~------库存:" + data.size());
}
/**
* 消费操作
*/
public void consume(int num){
if(data.size() == 0){//如果产品数量不足
System.out.println("消费操作--库存不足!");
}
//到这里,表示可以正常消费
for(int i = 0; i < num; i++){//消费num个产品
try {
data.take(); //take内部自动判断,消耗后库存是否充足,不足自我阻塞
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消费操作-->数量:" + num + ",消费成功~------库存:" + data.size());
}
}
3、sleep和wait的区别
Java笔试面试题整理第六波(修正版)的更多相关文章
- Java笔试面试题整理第八波
转载至:http://blog.csdn.net/shakespeare001/article/details/51388516 作者:山代王(开心阳) 本系列整理Java相关的笔试面试知识点,其他几 ...
- Java笔试面试题整理第五波
转载至:http://blog.csdn.net/shakespeare001/article/details/51321498 作者:山代王(开心阳) 本系列整理Java相关的笔试面试知识点,其他几 ...
- Java笔试面试题整理第四波
转载至:http://blog.csdn.net/shakespeare001/article/details/51274685 作者:山代王(开心阳) 本系列整理Java相关的笔试面试知识点,其他几 ...
- Java笔试面试题整理第七波
转载至:http://blog.csdn.net/shakespeare001/article/details/51388516 作者:山代王(开心阳) 1.super的作用 在Java中su ...
- Java笔试面试题整理第三波
转载至:http://blog.csdn.net/shakespeare001/article/details/51247785 作者:山代王(开心阳) 本系列整理Java相关的笔试面试知识点,其他几 ...
- Java笔试面试题整理第二波
转载至:http://blog.csdn.net/shakespeare001/article/details/51200163 作者:山代王(开心阳) 本系列整理Java相关的笔试面试知识点,其他几 ...
- Java笔试面试题整理第一波
转载至:http://blog.csdn.net/shakespeare001/article/details/51151650 作者:山代王(开心阳) 本系列整理Java相关的笔试面试知识点,其他几 ...
- Java工程师笔试题整理[校招篇]
Java工程师笔试题整理[校招篇] 隔着两个月即将开始校招了.你是不是也想借着这个机会崭露头角,拿到某些大厂的offer,赢取白富美.走上人生巅峰?当然如果你还没能打下Java基础,一定要先打 ...
- Java笔试面试题007
Java笔试面试题007 1.请用正則表達式匹配出QQ号(如果QQ号码为5-10位). 解答: ^ \d{5,10}$ 2.String, StringBuffer StringBuilder的差别. ...
随机推荐
- R语言scale与unscale函数
一.scale函数 R语言base库中自带数据标准化接口scale函数,函数介绍如下 Usage scale(x, center = TRUE, scale = TRUE) Arguments x: ...
- 四种常见的 POST 提交数据方式对应的content-type取值
application/x-www-form-urlencoded 这应该是最常见的 POST 提交数据的方式了.浏览器的原生 form 表单,如果不设置 enctype 属性,那么最终就会以 app ...
- 【深入理解Java集合框架】红黑树讲解(上)
来源:史上最清晰的红黑树讲解(上) - CarpenterLee 作者:CarpenterLee(转载已获得作者许可,如需转载请与原作者联系) 文中所有图片点击之后均可查看大图! 史上最清晰的红黑树讲 ...
- Learn how to use git
Git配置 $ git config --global user.name "Your Name" $ git config --global user.email "e ...
- jquery常用实例
$("#returnTop").click(function () { var speed=200;//滑动的速度 $('body,html').animate({ scrollT ...
- Problem B: 类的初体验(II)
Description 定义一个类Data,只有一个double类型的属性和如下3个方法: 1. 带1个参数的构造函数——初始化属性值为参数值. 2. double getValue()——获 ...
- JAVA数据库操作回滚小结
一:总结的原因 在最近的工作中,遇到了一个一对多关系多表数据传输,传送成功状态绑定在主数据表上,因为代码不健壮问题造成了主表传送状态更新失败,而子表数据就被重复插入.又由于数据传输频率很高,我们的测试 ...
- JVM Optimization
架构图 基本概念说明 堆(heap):数据存储,对象实例:空间往上增长,线程共享区:大小可通过-Xmx和-Xms配置 新生代(Young Generation):划分为Eden Space和两个Sur ...
- red hat防火墙的开启与关闭及状态查看方法
Redhat使用了SELinux来增强安全, 首先怎么查看防火墙的状态呢? a.可以通过如下命令查看iptables防火墙状态: chkconfig --list iptables b. selinu ...
- 使用jsoup轻松爬数据
刚刚学习爬虫,感觉使用jsoup爬虫挺容易的.记录一下自己爬取数据的过程. Jsoup介绍: Jsoup 是一个 Java 的开源HTML解析器,可直接解析某个URL地址.HTML文本内容.使用Jso ...