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的差别. ...
随机推荐
- python ----元组方法以及修改细节
元组的一级元素不可修改 #元组,有序 tu = (111,"alex",(11,22),[(33,44)],True,33,44,) v = tu[3][0][0] print(v ...
- 黄金点游戏 结队i项目
结对编程——黄金点游戏 本次的结对编程的项目是黄金点游戏,我的结对对象是冯雨倩,我们的编程能力都不太好,而且都对C语言更熟悉些,因此我们决定用C语言来实现. (1)分工:角色分配:冯雨倩是领航员, ...
- Xenserver7.6修改root密码
一:重启xenserver服务器 进入此界面时,先用上下建随便动下,解除4S倒计时,后按e键
- 读取txt数据存入数据库中
http://blog.csdn.net/daditao/article/details/18899469
- VC++、MFC Sqlite3数据库的使用
SQLite数据库是一种本地的轻型数据库,在存储一些本地的数据的时候,或者不需要用到Oracle,SQL2008之类的大型数据库的时候,Sqlite的优势就能够得到发挥.程序需要采集数据存储起来,可以 ...
- nginx 504 Gateway Time-out
#设定http服务器 http { include mime.types; #文件扩展名与文件类型映射表 default_type application/octet-stream; #默认文件类型 ...
- 2018idea如何布置tomcat修改URL后连接不到
以下连接 https://blog.csdn.net/cs825900618/article/details/86261019
- SpringMVC @RequestBody @RequestParam @PathVariable 等参数绑定注解详解
request 数据到handler method 参数数据的绑定所用到的注解和什么情形下使用: http://blog.csdn.net/walkerjong/article/details/794 ...
- 基于scrapy-redis分布式爬虫(简易)
redis分布式部署 1.scrapy框架是否可以自己实现分布式? - 不可以.原因有二. 其一:因为多台机器上部署的scrapy会各自拥有各自的调度器,这样就使得多台机器无法分配start_urls ...
- 【leetcode】427. Construct Quad Tree
problem 427. Construct Quad Tree 参考 1. Leetcode_427. Construct Quad Tree; 完