迁移仓库

This commit is contained in:
zeek 2020-02-23 22:23:40 +08:00
commit ae2f83f578
337 changed files with 10919 additions and 0 deletions

9
.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
.idea
*.swp
*.class
*.out
~*
_book
node_modules
.ropeproject
*.target

6
C_C++/.gitignore vendored Executable file
View File

@ -0,0 +1,6 @@
tags
*/out/*
*/out/
/out/*
*.o
*.out

1
C_C++/README.md Normal file
View File

@ -0,0 +1 @@
# C++

23
C_C++/make.sh Executable file
View File

@ -0,0 +1,23 @@
#!/usr/bin/env bash
#author: lzh
#echo `pwd`
if test -z $1;then
echo "./make.sh -[sources]"
exit 1
fi
echo "prepare"
if [ ! -d "./out" ];then
mkdir out
echo "mkdir out"
fi
echo "prepare finish \n compile"
resource="/sources/$1"
tmp=`echo ${resource} | sed -e "s:sources:out:g"`
out=`echo ${tmp} | sed "s:.c:\.o:g"`
outPath=`dirname ${out}`
if [ ! -d "`pwd`${outPath}" ];then
mkdir `pwd`${outPath}
echo "mkdir `pwd`${outPath}"
fi
gcc -g `pwd`${resource} -o `pwd`${out}
echo "finish"

View File

@ -0,0 +1,44 @@
#include <stdio.h>
#include <stdlib.h>
int main ()
{
char str[20];
printf("输入文件名:");
gets(str);
FILE *fp = fopen(str, "r");
if (fp == NULL )
{
printf("file open failed\n");
return 1;
}
char buff[255];
fgets(buff, 255, fp);
fclose(fp);
//printf("\n%s\n", buff);
int i = 0;
int left = 0, right = 0;
for ( i = 0 ; i < 255; i++ )
{
if ( buff[i] == '\0' || left < right )
{
break;
}
if ( buff[i] == '{' )
{
left ++;
}else if ( buff[i] == '}' )
{
right ++;
}
}
if ( left == right )
{
printf("花括号成对出现\n");
}
else
{
printf("花括号不成对出现\n");
}
return 0;
}

View File

@ -0,0 +1,10 @@
#include <stdio.h>
/**
* 1
*
*/
int increment1 ( int num )
{
return num + 1;
}

View File

@ -0,0 +1,10 @@
#include <stdio.h>
#include "increment.c"
#include "negate.c"
int main()
{
printf("increment(10) = %d\n", increment1(10));
printf("negate(10) = %d\n", negate1(10));
return 0;
}

View File

@ -0,0 +1,10 @@
#include <stdio.h>
/**
*
*
*/
int negate1 ( int num )
{
return 0 - num;
}

View File

@ -0,0 +1,26 @@
#include <stdio.h>
/**
*
*
*
**/
void squares ( int limit )
{
int i; /* loop counter */
/*
* Print table of squares
*/
for (i = 0; i < limit ; i ++)
{
printf("%d %d0", i, i * i);
}
printf("\n");
}
int main()
{
squares(7);
return 0;
}

View File

@ -0,0 +1,31 @@
#include <stdio.h>
int prime(int num)
{
if ( num <=2 ) return 0;
int i,result;
result = 0;
for ( i = 2; i < num ; i++ )
{
if ( num%i == 0 )
{
result = 1;
break;
}
}
return result;
}
int main()
{
int i;
for ( i = 0; i < 100 ; i++)
{
if ( prime(i) == 0 )
{
printf("%d\t", i);
}
}
printf("\n");
return 0;
}

View File

@ -0,0 +1,54 @@
#include <stdio.h>
/**
*
*/
void sort(int arr[],int len)
{
int i;
for (i = 0; i < len - 1; i++)
{
int j;
for ( j = i+1 ;j < len ;j++ )
{
if (arr[i] < arr[j])
{
int tmp;
tmp = arr[i];arr[i] = arr[j]; arr[j] = tmp;
}
}
}
}
int main(int argc,char *argv[])
{
if (argc != 4)
{
printf("error!\n");
return 1;
}
int arr[3];
arr[0] = atoi(argv[1]);
arr[1] = atoi(argv[2]);
arr[2] = atoi(argv[3]);
//printf("arr[0] = %d,arr[1] = %d,arr[2] = %d\n", arr[0],arr[1],arr[2]);
sort(arr,3);
//printf("arr[0] = %d,arr[1] = %d,arr[2] = %d\n", arr[0],arr[1],arr[2]);
if (arr[2] + arr[1] <= arr[0])
{
printf("构不成三角形\n");
}
else if ( arr[1] == arr[2])
{
printf("等腰三角形\n");
}
else if ( arr[0] == arr[1] && arr[1] == arr[2])
{
printf("正三角形\n");
}
else
{
printf("普通三角形\n");
}
return 0;
}

View File

@ -0,0 +1,7 @@
#include <stdio.h>
int main()
{
printf("hello word %s\n", "zeekling");
return 0;
}

View File

@ -0,0 +1,16 @@
#include <stdio.h>
#include <stdlib.h>
/*
* === FUNCTION ======================================================================
* Name: main
* Description:
* =====================================================================================
*/
int main ()
{
char hello[] = {'h','e','l','l','o',' ','w','o','r','l','d','\n',0};
printf("hello world\n");
printf(hello);
return EXIT_SUCCESS;
}

18
C_C++/sources/linux/test1.c Executable file
View File

@ -0,0 +1,18 @@
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
int catch(int sign);
int main(void){
signal(SIGINT, catch);//将信号与catch函数关联
printf("lingzhaohui \n");
sleep(10);
printf("end\n");
return 0;
}
int catch(int sign){
printf("\nyou pressed 'ctrl+c'\n");
return 1;
}

16
C_C++/sources/linux/test2.c Executable file
View File

@ -0,0 +1,16 @@
#include <stdio.h>
#include <unistd.h>
int main(void)
{
pid_t pid;
printf("father \n");
printf("fork \n");
pid = fork();
if(!pid)
printf("child \n");
else if(pid>0)
printf("i m the parent ,child pid %d\n",pid);
else
printf("fork failed \n");
}

16
C_C++/sources/offer/offer10.c Executable file
View File

@ -0,0 +1,16 @@
#include <stdio.h>
int go(int n){
int count = 0;
while(n){
count ++;
n = (n-1) & n;
}
return count;
}
int main(){
int count = go(9);
printf("%d\n",count);
return 0;
}

19
C_C++/sources/offer/offer11.c Executable file
View File

@ -0,0 +1,19 @@
#include <stdio.h>
int power(double base, int expo){
if(expo <= 0) return 1;
double result;
if((expo%2) == 0){
result = power(base,expo>>1)*power(base,expo>>1);
}else{
result = power(base,(expo-1)>>1)*power(base,(expo-1)>>1)*base;
}
return result;
}
int main(){
double result = power(2,4);
printf("%f\n",result);
return 0;
}

View File

@ -0,0 +1,10 @@
#include <stdio.h>
int main(){
int y = 1,x,a[] ={2,4,6,8,10},*p;
p = &a[1];
for(x = 0;x<3;x++){
y = y + *(p+x);
}
printf("%d \n ",y);
return 0;
}

0
C_C++/sources/test1/test1_1.c Executable file
View File

11
C_C++/sources/test1/test1_2.c Executable file
View File

@ -0,0 +1,11 @@
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *reverse(char *str){
}
int main(){
char *str = "hello world null";
}

19
README.md Normal file
View File

@ -0,0 +1,19 @@
## 目录
* [ORACLE](http://www.zeekling.cn/gogs/zeek/study/src/master/oracle)
* [Linux](http://www.zeekling.cn/gogs/zeek/study/src/master/linux)
* [Java知识](http://www.zeekling.cn/gogs/zeek/study/src/master/java)
* [Mysql](http://www.zeekling.cn/gogs/zeek/study/src/master/mysql)
* [c语言](http://www.zeekling.cn/gogs/zeek/study/src/master/c)
* [计算机网络](http://www.zeekling.cn/gogs/zeek/study/src/master/network)
* [操作系统](http://www.zeekling.cn/gogs/zeek/study/src/master/computer)
* [个人简历](http://www.zeekling.cn/gogs/zeek/study/src/master/resume)
## 结束语
一个爱学习,不怕孤单的小伙的读书笔记。
![呵呵呵,没看到图片吧](https://img.zeekling.cn/images/2020/02/22/1.md.png)
风骚小书生,呵呵哒

36
SUMMARY.md Normal file
View File

@ -0,0 +1,36 @@
# Summary
* [简介](README.md)
* [java相关](java/README.md)
* [linux相关](linux/README.md)
* [常见问题](linux/error.md)
* [树莓派使用](linux/树莓派使用教程.md)
* [awk详解](linux/awk/README.md)
* [Nginx参数调优](linux/nginx.md)
* [git详解](linux/git.md)
* [sed详解](linux/sed/README.md)
* [Linux常用命令](linux/commond.md)
* [centos相关](linux/centos/READMD.md)
* [centos问题总结](linux/centos/centos问题总结.md)
* [centos软件安装](linux/centos/hack软件安装.md)
* [C/C++](C_C++/README.md)
* [oracle相关](oracle/README.md)
* [docker下使用oracle](oracle/docker_oracle.md)
* [dual表的用途](oracle/dual表的用途.md)
* [oracle常用命令和函数](oracle/oracle常用命令和函数.md)
* [oracle常见问题](oracle/oracle常见问题.md)
* [oracle数据类型](oracle/oracle数据类型.md)
* [系统相关](oracle/sys/README.md)
* [dbms常用系统包详解](oracle/sys/dbms常用系统包详解.md)
* [oracle常见系统表的用法](oracle/sys/oracle常见系统表的用法.md)
* [python相关](python/README.md)
* [计算机网络](network/README.md)
* [简历](resume/README.md)
* [我的简历--markdown版](resume/mine.md)

BIN
basic/基础知识.docx Executable file

Binary file not shown.

75
book.json Normal file
View File

@ -0,0 +1,75 @@
{
"root":"./",
"author":"小令童鞋",
"description":"没有到不了的明天,只有回不了的昨天",
"plugins":["github",
"-sharing",
"-search",
"sharing-plus",
"-highlight",
"expandable-chapters-small",
"mathjax",
"splitter",
"disqus",
"3-ba",
"theme-comscore",
"search-plus",
"prism",
"prism-themes",
"github-buttons",
"ad",
"tbfed-pagefooter",
"ga",
"alerts",
"anchors",
"include-codeblock",
"ace"
],
"links":{
"sidebar":{
"主页":"http://www.zeekling.cn"
}
},
"pluginsConfig":{
"sharing":{
"douban":false,
"facebook":false,
"qq":false,
"qzone":false,
"google":false,
"all": [
"weibo","qq","qzone","google","douban"
]
},
"disqus":{
"shortName":"zeekling"
},
"ad":{
},
"include-codeblock":{
"template":"ace",
"unindent":true,
"theme":"monokai"
},
"tbfed-pagefooter":{
"Copyright":"&copy zeekling.cn",
"modify_label":"文件修改时间",
"modify_format":"YYYY-MM-DD HH:mm:ss"
},
"3-ba":{
"token":"zeekling"
},
"ga":{
"token":"zeekling",
"configuration":{
"cookieName":"zeekling",
"cookieDomain":"book.zeekling.cn"
}
},
"github":{"url":"http://www.zeekling.cn/gogs/zeek"},
"theme-default": {
"showLevel": true
}
}
}

2
computer/REAMME.md Executable file
View File

@ -0,0 +1,2 @@
# 计算机操作系统复习

4
java/.gitignore vendored Executable file
View File

@ -0,0 +1,4 @@
tags
*/out/*
*/out/
/out/*

262
java/README.md Normal file
View File

@ -0,0 +1,262 @@
# java 部分
## java基础知识
* 面向对象的三大特征
* 继承:继承是类与类的一种关系,比较像集合中的从属于关系。
* 封装:隐藏类的基本信息,不允许外部程序直接访问,而是通过该类的方法实现对隐藏信息的操作和访问。
* 多态:方法的重写、重载与动态连接构成多态性;
* 面向对象的六大原则 【参考[设计模式](http://www.zeekling.cn/gogs/zeek/designPattern/src/master/principle)】
* 单一职责原理:一个类只负责一项职责。
* 里氏替换原则:劲量不要重写父类的已经实现了的方法,可以用接口等其他方法绕开。
* 依赖倒置原则:高层模块不应该依赖底层模块,二者应依赖其抽象;抽象不应该依赖细节;细节应该依赖抽象。
* 接口隔离原则:客户端不应该依赖其他不需要的接口;一个类对另一个类的依赖应该建立在最小的接口上。
* 迪米特法则:又叫做最小知道原则。就是一个类对自己依赖的类知道越少越好。
* 开闭原则:尽量通过扩展软件实体行为来实现变化。
* 数据类型
* 基本数据类型
* 数值类型
* 整型:int(4字节)、short(2字节)、long(8字节)、char(2字节)、byte(1字节)、
* 浮点型:float(4字节)、double(8字节)
* boolean: boolean(1字节)
* 引用数据类型:数组、对象
* 强引用:用关键`new`出来的对象,强引用锁指向的对象在任何时候都不会被回收
* 软引用:用来描述有用但非必须的对象,在内存不足的时候可以回收
* 弱引用:用来描述非必须的对象,但是它的强度比软引用更弱一些,被弱引用关联的对象只能生存到下一次垃圾收集发送之前。
* 虚引用:虚引用也称为幽灵引用或者幻影引用,它是最弱的一种引用关系。一个持有虚引用的对象,和没有引用几乎是一样的,随时都有可能被垃圾回收器回收。
* java集合
![集合类总图](http://www.zeekling.cn/gogs/zeek/study/raw/master/java/pics/list.png)
* Collection:集合类的根接口list和set都继承自此接口
* List有序,可以重复一般用index标示顺序
* LinkedList底层用双链表实现:增加删除效率高
* ArrayList底层用数组实现:查找效率高
* Vector实现了一个动态数组。和ArrayList相似但是有以下不同vector是同步的
vector包含了许多传统方法或者只是需要一个可以改变大小的数组的情况。
* Stack:先进后出
* set无序不能有重复的元素
* HashSet:HashSet不存入重复元素的规则.使用hashcode和equals
* LinkedHashSet:是对LinkedHashMap的简单包装对LinkedHashSet的函数调用都会转换成合适的LinkedHashMap方法
* TreeSet:让存入的元素自定义比较规则;给TreeSet指定排序规则
* Queue
* Map由键值对组成,和Collection完全不相干是另一个接口
* Hashtable同步的、线程安全的不能接受为null的键值不到万不得已不要使用。
* HashMap非同步、线程不安全,一般不要求线程安全的情况下建议使用
* LinkedHashMap: 是HashMap+LinkedList即它既使用HashMap操作数据结构又使用LinkedList维护插入元素的先后顺序。
java 7 hashmap实现原理
![hashmap实现原理](http://www.zeekling.cn/gogs/zeek/study/raw/master/java/pics/hashmap1.jpeg)
java8 实现原理
![java8 实现原理](http://www.zeekling.cn/gogs/zeek/study/raw/master/java/pics/hashmap2.png)
* ConcurrentHsahMap可以用来代替HashTable而且比HashTable的扩展性好。
![ConcurrentHsahMap实现原理](http://www.zeekling.cn/gogs/zeek/study/raw/master/java/pics/ConcurrentHashMap.png)
* TreeMap:是一个有序的key-value集合它是通过红黑树实现的。是SortedMap的一个实现类
* WeakHashMap:
* IdentifyHashMap:
* 并发集合类
* java.util.concurrent
* Executor:一个接口其定义了一个接收Runnable对象的方法executor其方法签名为executor(Runnable command),
* ExecutorService:是一个比Executor使用更广泛的子类接口其提供了生命周期管理的方法以及可跟踪一个或多个异步任务执行状况返回Future的方法
* Futurecallable实现的存在返回值的并发编程
* CountDownLatch可以用来在一个线程中等待多个线程完成任务的类
* Vector
* io流
![io详解](http://www.zeekling.cn/gogs/zeek/study/raw/master/java/pics/io.png)
* 根据处理数据的类型
* 字节流:字节流因为操作的是字节,所以可以用来操作媒体文件。
* 字符流字符流中的对象融合了编码表也就是系统默认的编码表。我们的系统一般都是GBK编码。字符流只用来处理文本数据字节流用来处理媒体数据。
* 根据数据流向
* 输入流
* 输出流
* RandomAccessFile:
* 对象序列化
* NIO(非阻塞IO)
* IO和NIO的区别
![IO和NIO的区别](http://www.zeekling.cn/gogs/zeek/study/raw/master/java/pics/nio_and_io.png)
* AIO (异步IO)
* 多线程
* 多线程的实现方式
* 继承自Thread类(不能线程共享)
* 实现Runnable接口(不可以返回值)
* 实现Callable接口(可以抛出异常、返回值)
* ThreadPoolExecutor
* ThreadPoolExecutor的策略
* 线程数量未达到corePoolSize则新建一个线程(核心线程)执行任务
* 线程数量达到了corePools则将任务移入队列等待
* 队列已满,新建线程(非核心线程)执行任务
* 队列已满总线程数又达到了maximumPoolSize,就会(RejectedExecutionHandler)抛出异常
* 常见四种线程池
* CachedThreadPool:线程数无限制;有空闲线程则复用空闲线程,若无空闲线程则新建线程;一定程序减少频繁创建/销毁线程,减少系统开销.
* FixedThreadPool:可控制线程最大并发数(同时执行的线程数);超出的线程会在队列中等待
* ScheduledThreadPool:支持定时及周期性任务执行。
* SingleThreadExecutor:有且仅有一个工作线程执行任务;所有任务按照指定顺序执行,即遵循队列的入队出队规则
* Executors
* 线程同步
* 同步方法:
* 同步代码块:synchronized 关键字在编译之后会在同步块的前后加上monitorenter和monitorexit,在执行monitorenter时需要获取锁如果占用所得对象是自己则需要将锁计数器加1,monitorexit时将锁计数器减1如果为0则释放锁
* 关键字volatile:
* 防止指令重排
* 编译器重排序。编译器在不改变单线程程序语义的前提下,可以重新安排语句的执行顺序;
* 处理器重排序。如果不存在数据依赖性,处理器可以改变语句对应机器指令的执行顺序;
* 实现可见性,不保证原子性
* 可见性volatile保证线程所在空间中的volatile修饰的变量的值是最新的;
* 不保证原子性:两个线程对volatile修饰的变量同时进行赋值操作可能导致两个线程对该变量进行一次赋值。
* Reentrantlock:可重入锁,synchronized和Reentrantlock都是重入锁区别如下:
* synchronized:
1. 依赖JVM实现加入偏向锁之后性能和Reentrantlock差不多了
2. 使用比较方便简洁,由编译器去实现加锁和释放;
3. 只能是非公平锁;
* Reentrantlock:
1. 主要依赖代码控制实现,可以避免进入内核态的阻塞;
2. 需要手动加锁和释放锁,容易由于忘记释放锁导致死锁;
3. 既可以是公平锁也可以是非公平锁;
4. 提供Condition类可以分组唤醒线程
5. 能够中断等待线程;
* 使用局部变量实现线程的同步,如:ThreadLocal。
* 相关名词
* 对象锁、互斥锁、共享锁、公平锁、非公平锁([公平锁和非公平锁的比较](http://blog.csdn.net/fw0124/article/details/6672522))、
* 偏向锁:它会偏向于第一个访问锁的线程,如果在接下来的运行过程中,该锁没有被其他的线程访问,则持有偏向
锁的线程将永远不需要触发同步。如果在运行过程中,遇到了其他线程抢占锁,则持有偏向锁的线程会被挂起,
JVM会尝试消除它身上的偏向锁将锁恢复到标准的轻量级锁。引入偏向锁是为了在无多线程竞争的情况下尽量
减少不必要的轻量级锁执行路径。
* 原子操作、原子性、可见性
* [悲观锁和乐观锁 ](http://www.hollischuang.com/archives/934)
* [共享锁和排他锁](http://www.hollischuang.com/archives/923)
* 线程的交互
* notify()、 notifyAll()、wait()
* 反射
## java虚拟机
### 简述
java虚拟机我看过周志明的《深入理解java虚拟机》和周志明等人翻译的《java虚拟机规范(java SE 8版)》
### 结构
* 内存管理
* 虚拟机栈(非共享):
* 栈帧
* 局部变量表:局部变量数组包含了方法执行过程中的所有变量,包括 this 引用、所有方法参数、其他局部变量。
* 返回值:
* 操作数栈
* 类当前方法的运行时常量池引用
* java堆共享堆包括新生代( Eden、Survivor(from)、Survivor(to) )、老年代。
* 本地方法栈(非共享)
* 程序计数器(非共享)
* 方法区共享也可以说在堆中方法区又叫非堆用来区分对内存在hotsport虚拟机中方法区又叫做永久带.用来存放类信息,常量等和类相关的数据.
* 元空间:1.8引入的,用来替换方法区(永久代);不再虚拟机中,使用的是本地内存,取决于电脑的内存大小
***内存结构图***
1.7及以前版本java内存分布图
![jvm内存管理](http://www.zeekling.cn/gogs/zeek/study/raw/master/java/pics/jvm.jpg)
1.8 内存分布图:
![jvm内存管理](http://www.zeekling.cn/gogs/zeek/study/raw/master/java/pics/jvm.png)<br>
* 对象
* 对象的创建
* 对象的内存布局
* 对象头
* MarkWord:对象的MarkWord部分占4个字节其内容是一系列的标记位比如轻量级锁的标记位偏向锁标记位等等。
* Class对象指针:其指向的位置是对象对应的Class对象其对应的元数据对象的内存地址.
* 实例数据:存放属性信息,包括父类的信息。
* 对齐填充(有些对象没有,具体不太懂):Java对象在内存中将以8字节对齐也就是对象的总大小必须是8字节的整数倍。
* 对象的访问
* 指针方式访问hotspot 虚拟机用的就是指针方式访问):指针访问方式访问方式比句柄方式快,节省一次指正定位带来的时间开销。
* 句柄方式访问其他虚拟机句柄池中存放的是稳定的句柄当对象被移动时只需要改变句柄的实例数据就行不需要改变reference本身的值。
***普通对象的内存分布***
![mei对象](http://www.zeekling.cn/gogs/zeek/study/raw/master/java/pics/object.JPEG)
***数组对象的内存分布***
![mei对象](http://www.zeekling.cn/gogs/zeek/study/raw/master/java/pics/object_arr.JPEG)
* 垃圾回收
* 判断对象已死
* 引用计数法(无法判断循环引用的对象是否已死):每个对象都有一个引用计数器对象每被引用一次就加1对象被释放就减1引用计数为0表示可以被回收。
* 可达分析法如果对象能够到达root就认为对象不可回收。root对象
* 被启动类bootstrap加载器加载的类和创建的对象
* jvm运行时方法区类静态变量(static)引用的对象
* jvm运行时方法去常量池引用的对象
* jvm当前运行线程中的虚拟机栈变量表引用的对象
* 本地方法栈中(jni)引用的对象
* 垃圾收集算法
* 标记-清除算法(老年代,标记-清理算法容易产生碎片):标记阶段标记可回收的对象,请理阶段清理被标记的对象所占用的空间
* 复制算法(新生代,由于新生代对象存活较少,利用复制算法效率较高):按内存将容量将内存分为等大小的两块,每次只使用其中的一块,当一块的内存满了之后将存活对象复制到另一块上面去。
* 标记-整理算法(老年代):标记阶段标记可回收的对象,整理阶段将存活的对象移动到对象的另一边,清除边界以外的对象。
* 分代收集算法:新生代用复制算法(新生代存活的对象比较少),老年代用标记-清除和标记-整理算法
* 垃圾收集器(共六个垃圾收集器)
* 新生代收集器(新生代收集器一般都利用复制算法)
* Serial收集器复制算法
* ParNew收集器复制算法
* Parallel Scavenge收集器复制算法
* 老年代收集器
* Serial Old 收集器(标记-整理算法)
* CMS收集器标记-清除算法): 初始标记、 并发标记、 重新标记、 并发清除
* Parallel Old 收集器(标记-整理算法)
* G1收集器
* 步骤 初始标记、 并发标记、最终标记、筛选标记
* 特点: 并行与并发、分代收集、空间整合、可预测停顿
* class 文件
* class文件的结构
* 魔数:判断class文件是否被虚拟机接受的Class文件魔术固定值是0xCAFEBABE
* 版本号(主版本号、次版本号):主板本和副版本共同构成了Java文件的格式版本
* 访问标志(标识一些类或者接口的访问信息):用于表示某个类或者接口的访问权限及基础属性
* 类索引(this_class):this_class的值必须是对constant_pool表中项目的一个有效索引值,表示这个Class文件所定义的类或接口。
* 父类索引(super_class):对于类来说super_class的值必须为0或者是对constant_pool表中项目的一个有效索引值。
* 接口数/接口表:
* 字段计数器:它用于表示该类或接口声明的类字段或者实例字段。
* 常量池计数器:constant_pool_count的值等于constant_pool表中的成员数加1。
* 常量池(主要存放两大类常量),常量池的索引范围是1至constant_pool_count1。
* 字面量
* 符号引用
* 字段表集合(含有字段访问标志)
* 方法数/方法表:
* 属性数/属性表:
* 类加载机制
* 类加载过程
* 加载
* 链接
* 验证:
* 准备:为类变量等赋初始值。如:`public static int a = 123;` 初始值为0不是123.
* 解析:将符号引用转化为直接引用的过程。
* 初始化
* 使用
* 卸载
* 双亲委派模型
* 启动类加载器:加载`${JAVA_HOME}/jre/lib/`下面的jar包所有以`java.*`的class都是由启动类加载器加载的。
* 扩展类加载器:加载`${JAVA_HOME}/jre/ext/*.jar`
* 应用程序类加载器:用户指定的类。
* 用户自定义类加载器:
* 破坏双亲委派模型
* 线程上下文类加载器
* 虚拟机字节码执行引擎(这部分还没有看懂,就不具体列提纲了)
*
* 高效并发
* 内存间的交互
* lock锁定作用于主存的变量
* unlock解锁作用于主存的变量
* read读取作用于主存的变量
* load载入作用于工作内存的变量
* use使用作用于工作内存的变量
* assign赋值作用于工作内存的变量
* store存储作用于工作内存的变量
* write写入作用于主存的变量
## 算法部分
### 简述
java部分我主要看过[《剑指offer》](http://pan.baidu.com/s/1c1ZmCww)和[《程序员面试金典》](http://www.duokan.com/book/63706)两本书。感觉两本书都挺不错的。
### 《 剑指offer》
[剑指offer面试题目](https://github.com/lzh984294471/job/tree/master/job/java/com/thinker/offer)
### 《 程序员面试金典》
#### 面试考题型目录
* [数组与字符串](https://github.com/lzh984294471/job/tree/master/job/java/com/thinker/test/test1)
* [链表](https://github.com/lzh984294471/job/tree/master/job/java/com/thinker/test/test2)
* [栈与队列](https://github.com/lzh984294471/job/tree/master/job/java/com/thinker)
* [树与图](https://github.com/lzh984294471/job/tree/master/job/java/com/thinker)
* [位操作](https://github.com/lzh984294471/job/tree/master/job/java/com/thinker)
* [智力题](https://github.com/lzh984294471/job/tree/master/job/java/com/thinker)
* [数学与概率](https://github.com/lzh984294471/job/tree/master/job/java/com/thinker)
* [面向对象设计](https://github.com/lzh984294471/job/tree/master/job/java/com/thinker)
* [递归和动态规划](https://github.com/lzh984294471/job/tree/master/job/java/com/thinker)
* [扩展性与存储限制](https://github.com/lzh984294471/job/tree/master/job/java/com/thinker)
* [排序与查找](https://github.com/lzh984294471/job/tree/master/job/java/com/thinker)
### 脚本
脚本compile.sh 没有完成

25
java/javaCompile.sh Executable file
View File

@ -0,0 +1,25 @@
#!/usr/bin/env bash
#################################################
# author:lzh #
# usage:used for compile single java file #
#################################################
if test -z $1;then
read -p "Please input your java file name:" file
else
file=$1
fi
while test -z ${file}
do
echo -e "\033[31mYou input nothing!!!!!!\033[037m"
read -p "Please input your java file name:" file
done
files=`find -name "${file}.java"`
echo ${files}
if test -z ${files};then
echo -e "\033[31mDo not find java file\033[37m"
exit 1
fi
javac -g -source 1.8 -target 1.8 -d ./out/ ${files} -encoding UTF-8 &&
echo -e "\033[32mCompile finish *_*\033[0m \033[37m" ||
echo -e "\033[31mCompile error \033[0m \033[37m"

16
java/make.sh Executable file
View File

@ -0,0 +1,16 @@
#!/usr/bin/env bash
#author:zeekling
echo "compiling"
if [ ! -d target ];then
mkdir target
else
rm -rf target/*
fi
file=`find -name "*.java"`
echo "copying file"
all=`find -name "*"`
javac -g -source 8 -target 8 -d ./target/ ${file} -encoding UTF-8 &&
echo -e "\033[32mcompile finish *_*\033[0m \033[37m" ||
echo -e "\033[31mcompile error \033[0m \033[37m"

2
java/maven/maven.md Normal file
View File

@ -0,0 +1,2 @@
gpg maven 验证

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

BIN
java/pics/handler.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 164 KiB

BIN
java/pics/hashmap1.jpeg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

BIN
java/pics/hashmap2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
java/pics/io.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

BIN
java/pics/jvm.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

BIN
java/pics/jvm.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

BIN
java/pics/list.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

BIN
java/pics/nio_and_io.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

BIN
java/pics/object.JPEG Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

BIN
java/pics/object_arr.JPEG Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

BIN
java/pics/reference.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

31
java/redis.md Normal file
View File

@ -0,0 +1,31 @@
## redis 复习
### redis 特点
1. 速度快因为数据存在内存中类似于HashMapHashMap的优势就是查找和操作的时间复杂度都是O(1)
2. 支持丰富数据类型支持stringlistsetsorted sethash
3. 支持事务,操作都是原子性,所谓的原子性就是对数据的更改要么全部执行,要么全部不执行
- Multi-开启一个事务
- exec-负责触发并执行事务中的所有命令
4. 丰富的特性可用于缓存消息按key设置过期时间过期后将会自动删除
### redis 提供 6种数据淘汰策略
- voltile-lru从已设置过期时间的数据集server.db[i].expires中挑选最近最少使用的数据淘汰
- volatile-ttl从已设置过期时间的数据集server.db[i].expires中挑选将要过期的数据淘汰
- volatile-random从已设置过期时间的数据集server.db[i].expires中任意选择数据淘汰
- allkeys-lru从数据集server.db[i].dict中挑选最近最少使用的数据淘汰
- allkeys-random从数据集server.db[i].dict中任意选择数据淘汰
- no-enviction驱逐禁止驱逐数据
### Redis是单进程单线程的
redis利用队列技术将并发访问变为串行访问消除了传统数据库串行控制的开销
### redis的并发竞争问题如何解决
1. 客户端角度为保证每个客户端间正常有序与Redis进行通信对连接进行池化同时对客户端读写Redis操作采用内部锁synchronized。
2. 服务器角度利用setnx实现锁
- setnx(lockkey, 1) 如果返回0则说明占位失败如果返回1则说明占位成功
- expire()命令对lockkey设置超时时间为的是避免死锁问题。
- 执行完业务代码后可以通过delete命令删除key
### redis常见性能问题和解决方案

80
java/src/Program.java Normal file
View File

@ -0,0 +1,80 @@
/**
* @author 令照辉 [zeekling@163.com]
* @version 1.0
* @apiNote
* @since 2018-06-27
*/
public class Program {
/**
*
* @param arr 需要排序的数组
*/
private static void mergeSort(int[] arr) {
int[] tmp = new int[arr.length];
internalMergeSort(arr, tmp, 0, arr.length - 1);
}
/**
*
* @param arr 需要排序的数组
* @param tmp 暂时存放数据
* @param left
* @param right
*/
private static void internalMergeSort(int[] arr, int[] tmp, int left, int right) {
if (left < right) {
int middle = (left + right) / 2;
internalMergeSort(arr, tmp, left, middle);
internalMergeSort(arr, tmp, middle + 1, right);
mergeArray(arr, tmp, left, middle, right);
}
}
/**
*
* @param arr
* @param tmp
* @param left
* @param middle
* @param right
*/
private static void mergeArray(int[] arr, int[] tmp, int left, int middle, int right) {
int i = left, j = middle + 1, k = 0;
while (i <= middle && j <= right) {
if (arr[i] <= arr[j]) {
tmp[k++] = arr[i++];
} else {
tmp[k++] = arr[j++];
}
}
while (i <= middle) tmp[k++] = arr[i++];
while (j <= right) tmp[k++] = arr[j++];
for (i = 0; i < k; i++)
arr[left + i] = tmp[i];
}
/**
* 输出格式第11大的数除前十个大数以外的所有数字的中位数
* @param args
*/
public static void main(String[] args) {
if (args == null || args.length <= 10) return;
int[] arr = new int[args.length];
for (int i = 0;i<args.length;i++){
arr[i] = Integer.valueOf(args[i]);
}
mergeSort(arr);
int even = (10 + arr.length)%2;//判断是否为偶数
if (even == 0){
double add = arr[(10 + arr.length -1)/2] + arr[(10 + arr.length +1)/2];
double middle = (add)/2;
System.out.println(arr[10]+","+ middle);
}else{
int middle = arr[(10 + arr.length)/2];
System.out.println(arr[10]+","+ middle);
}
}
}

View File

@ -0,0 +1,35 @@
package com.thinker.bishi;
/**
*
*/
public interface Test {
public static void main(String[] args) {
Test test = new Test() {
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return super.toString();
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
};
}
}

View File

@ -0,0 +1,36 @@
package com.thinker.bishi.beiyou;
import java.util.Scanner;
/**
* @author lzh
* http://code.bupt.edu.cn/problem/p/84/
*/
public class SingleNumber {
private static int result(int[] arr,int len){
int check = 0;
int chongfu = 0;
// find chongfu
for(int i=0;i<len;i++){
int val = arr[i];
if((check & (1<<val)) != 0){
chongfu |= (1<<val);
}
check |= (1<<val);
}
chongfu = check & (~chongfu);
return chongfu;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = Integer.parseInt(in.nextLine());
String[] numStr = (in.nextLine()).split(" ");
int[] nums = new int[num];
for(int i=0;i<num;i++){
nums[i] = Integer.parseInt(numStr[i]);
}
System.out.println(result(nums,num));
}
}

View File

@ -0,0 +1,33 @@
package com.thinker.bishi.beiyou;
import java.util.Scanner;
/**
* @author lzh
*/
public class Test {
public static int search(int[] a, int fromIndex, int toIndex, int key) {
if(fromIndex > toIndex) {
return -1;
}
int mid = (fromIndex + toIndex) >> 1;
if(a[mid] < key) {
return search(a, mid + 1, toIndex, key);
} else if(a[mid] > key) {
return search(a, fromIndex, mid - 1, key);
} else {
return mid;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int key = in.nextInt();
int len = in.nextInt();
int[] arr = new int[len];
for(int i=0;i<len;i++){
arr[i] = in.nextInt();
}
System.out.println(search(arr,0,len-1,key));
}
}

View File

@ -0,0 +1,4 @@
/**
* @author lzh
*/
package com.thinker.bishi.beiyou;

View File

@ -0,0 +1,93 @@
package com.thinker.bishi.huawei;
import java.util.Scanner;
/**
* @author lzh
* @apiNote one two three four five six seven eight nine zero double ol
* 还有一个表示零的忘记是什么了只记得好像是以o开头的好像还是两位就暂时用
* ol代替吧原理一样的*_*
*/
public class Convert {
private static StringBuilder pri = new StringBuilder();
private static boolean isError = false;
/**
* @apiNote 检查字符串中有没有数字
* @param str str
* @return boolean
*/
private static boolean check(String str){
boolean result = true;
char[] tmp = str.toCharArray();
for(int i=0;i<tmp.length;i++){
result = ((int)tmp[i] >= 65 && (int)tmp[i] <= 90) ||
((int)tmp[i] >= 97 && (int)tmp[i] <= 122);
}
return result;
}
/**
* @apiNote 利用递归判断当前字母表示的数字
* @param str char[]
* @param curr 当前位置
* @param flag 前一个是否为double
*/
private static void result(char[] str,int curr,boolean flag){
if(!(curr<str.length))return;
boolean currFlag = false;
int currNum = 0;
if(str[curr] == 'f' || str[curr] == 'F'){
if(str[curr + 1] == 'i' || str[curr + 1] == 'I'){ curr += 4;currNum = 5;}
else if(str[curr + 1] == 'o' || str[curr + 1] == 'O'){ curr += 4;currNum = 4;}
}else if(str[curr] == 't' || str[curr] == 'T'){
if(str[curr + 1] == 'w' || str[curr + 1] == 'W'){ curr += 3;currNum = 2;}
else if(str[curr + 1] == 'h' || str[curr + 1] == 'H'){ curr += 5;currNum = 3;}
}else if(str[curr] == 's' || str[curr] == 'S'){
if(str[curr + 1] == 'i' || str[curr + 1] == 'I'){ curr += 3;currNum = 6;}
else if(str[curr + 1] == 'e' || str[curr + 1] == 'E'){ curr += 5;currNum = 7;}
}else if(str[curr] == 'o' || str[curr] == 'O'){
if(str[curr + 1] == 'n' || str[curr + 1] == 'N'){ curr += 3;currNum = 1;}
else if(str[curr + 1] == 'l' || str[curr + 1] == 'L'){ curr += 2;currNum = 0;}
}else if(str[curr] == 'e' || str[curr] == 'E'){
curr += 5;currNum = 8;
}else if(str[curr] == 'n' || str[curr] == 'N'){
curr += 4; currNum = 9;
}else if(str[curr] == 'd' || str[curr] == 'D') {
curr += 6; currFlag = true;
}else {
isError = true;
return;
}
if(flag && currFlag) {
isError = true;
return;
}
if(flag) pri.append(currNum).append(currNum);
else pri.append(currNum);
result(str, curr, currFlag);
}
/**
*
* @param str 输入的字符串
*/
private static void result(String str){
if(!check(str)) {
System.out.println("error");
return;
}
result(str.toCharArray(),0,false);
if(!isError)System.out.println(pri.toString());
else System.out.println("error");
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int len = Integer.parseInt(in.nextLine());
for(int i=0;i<len;i++){
String str = in.nextLine();
result(str);
}
}
}

View File

@ -0,0 +1,35 @@
package com.thinker.bishi.huawei;
import java.util.Scanner;
public class CountCharNum{
public static int count(String s1,char s2){
if(s1 == null || "".equals(s1)) return 0;
int count = 0;
int flag = 0;
if((int)s2 >= 65 && (int)s2 <= 90)flag = 1;
if((int)s2 >= 97 && (int)s2 <= 122) flag = 2;
for(int i=0;i<s1.length();i++){
if(s2 == s1.charAt(i))count ++;
if(flag == 1){
if((char)(s2+32) == s1.charAt(i)) count ++;
}
if(flag == 2){
if((char)(s2-32) == s1.charAt(i)) count ++;
}
}
return count;
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String s1 = in.nextLine();
char s2 = ' ';
if(in.hasNextLine()){
s2 = in.nextLine().charAt(0);
}
System.out.println(count(s1,s2));
}
}

View File

@ -0,0 +1,22 @@
package com.thinker.bishi.huawei;
import java.util.Scanner;
public class CountLastWordLength{
public static int count(String str){
if(null == str || "".equals(str)) return 0;
int count = 0;
for(int i=str.length()-1;i>=0;i--){
if(str.charAt(i) != ' ')count += 1;
else break;
}
return count;
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String inStr = in.nextLine();
System.out.println(count(inStr));
}
}

View File

@ -0,0 +1,47 @@
package com.thinker.bishi.huawei;
import java.util.Scanner;
/**
* @author lzh
* @apiNote 华为笔试第二道题题目记得不太清楚
*/
public class HexChange {
private static StringBuilder result = new StringBuilder();
private static void hexChange(int num,int hex){
if(hex == 0) return ;
int residue = num % hex;
num = num/hex;
result.append(residue);
if(num == 0) return;
hexChange(num,hex);
}
private static int getResult(int num,int hex){
hexChange(num,hex);
StringBuilder tmp = new StringBuilder();
for(int i=0;i<result.length();i++){
tmp.append(result.charAt(result.length()-1-i));
}
result = new StringBuilder();
return Integer.parseInt(tmp.toString());
}
private static void result(int num){
if(num > 0 && num <= 10){
Integer sum = 0;
int hex = 2;
while (hex<=num){
sum += getResult(num,hex);
hex ++;
}
System.out.println(sum);
}else {
System.out.println("error");
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
result(num);
}
}

View File

@ -0,0 +1,29 @@
package com.thinker.bishi.nanyang;
import java.util.Scanner;
/**
* @author lzh
* <p>a+b=?</p>
*/
public class Add {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt(),b = in.nextInt();
System.out.println(add(a,b));
}
/**
* a+b=?
* @param a a
* @param b b
* @return int
*/
private static int add(int a,int b){
int t ;
while (b != 0){
t = a^b;b = (a&b) << 1; a = t;
}
return a;
}
}

View File

@ -0,0 +1,24 @@
package com.thinker.bishi.offer;
/**
* @author lzh
* @apiNote 判断一个字符串中是否只含有相同的子字符串子串长度>=2
*/
public class CheckSameSubString {
public static boolean go(String str){
if(null == str || str.length() <= 2) return false;
for(int i=0;i<str.length()-2;i++){
String tmp = str.substring(i,i+2);
int index = str.indexOf(tmp,i+2);
if(index != -1){
return true;
}
}
return false;
}
public static void main(String[] args) {
System.out.println(go("12345623"));
System.out.println(go("adghjkj"));
}
}

View File

@ -0,0 +1,30 @@
package com.thinker.bishi.offer;
/**
* @author lzh
*/
public class EqualCount {
private static int count = 0;
private static int realResult = 6;
public static void go(int[] opts,int result,int current,String sym){
if(current >= opts.length-1) {
if(result == EqualCount.realResult)
count += 1;
return;
}
if("+".equals(sym))
result += opts[current];
if("-".equals(sym))
result -= opts[current];
go(opts, result, current+1, "+");
go(opts, result, current+1, "-");
}
public static void main(String[] args) {
int opts[] = new int[]{1,2,3,4,5,6,7,8,9};
go(opts,opts[0],1,"+");
go(opts,opts[0],1,"-");
System.out.println(count);
}
}

View File

@ -0,0 +1,36 @@
package com.thinker.bishi.offer;
/**
* @author lzh
* @apiNote 大数相加
*/
public class LargeNumPlus {
private static String plus(String s1,String s2){
if(s1 == null || s2 == null) return "0";
StringBuilder result = new StringBuilder();
int carry = 0;
int tmp ;
//plus
for(int i=s1.length()-1,j=s2.length()-1;i>=0 || j>=0;i--,j--){
tmp = 0;
if(i>=0) tmp += s1.charAt(i)-48;
if(j>=0) tmp += s2.charAt(j)-48;
tmp += carry;
carry = tmp/10;
result.append(tmp%10);
}
//旋转
for(int i=0;i<result.length()-1-i;i++){
char tmpChar = result.charAt(i);
result.setCharAt(i,result.charAt(result.length()-1-i));
result.setCharAt(result.length()-1-i,tmpChar);
}
return result.toString();
}
public static void main(String[] args) {
String s1 = "1232";
String s2 = "128";
System.out.println(plus(s1,s2));
}
}

View File

@ -0,0 +1,21 @@
package com.thinker.bishi.offer;
/**
* @author lzh
*/
public class Offer_10 {
public static int go(int n){
int count = 0;
while(n > 0){
count++;
n = (n-1) & n;
}
return count;
}
public static void main(String[] args) {
int result = go(9);
System.out.println(result);
}
}

View File

@ -0,0 +1,25 @@
package com.thinker.bishi.offer;
/**
* @author lzh
*/
public class Offer_11 {
public static double power(int expo,double base){
if(expo <= 0){
return 1;
}
double result;
if((expo%2) == 0){
result = power(expo>>1, base)*power(expo>>1, base);
}else {
result = power((expo-1)>>1, base)*power((expo-1)>>1, base)*base;
}
return result;
}
public static void main(String[] args) {
double result = power(3,3);
System.out.println(result);
}
}

View File

@ -0,0 +1,44 @@
package com.thinker.bishi.offer;
/**
* 剑指offer面试题三
* 题目在一个二维数组中每一行都按照从左到右递增的顺序排序每一列都按照从上到下递增的顺序排序请完成
*/
public class Offer_3 {
private static int[][] arr= new int[][]{
{1,2,8,9},
{2,4,9,12},
{4,7,10,13},
{6,8,11,15}
};
private static int rows = 0;
private static int lines = 0;
public static void init(){
lines = arr.length;
rows = arr[0].length;
}
public static boolean go(int find){
boolean flag = false;
int i = 0,j = rows-1;
while (i<lines && j>=0){
if(arr[i][j]==find){
flag = true;break;
}else if(arr[i][j] > find){
j--;
}else if(arr[i][j] < find){
i++;
}
}
return flag;
}
public static void main(String[] args) {
init();
boolean exit = go(7);
System.out.println(exit);
}
}

View File

@ -0,0 +1,20 @@
package com.thinker.bishi.offer;
/**
* @author lzh
* 回文数
*/
public class Palindrome {
private static boolean go(int[] arr){
if(arr == null || arr.length ==0) return false;
for(int i=0,j=arr.length-1;j>=i;i++,j--){
if(arr[i] != arr[j]) return false;
}
return true;
}
public static void main(String[] args) {
int[] arr = new int[]{1,2,2,1};
System.out.println(go(arr));
}
}

View File

@ -0,0 +1,39 @@
package com.thinker.bishi.offer;
import java.util.ArrayList;
import java.util.Stack;
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public class PrintListFromTailToHead{
public static ArrayList<Integer> printListFromTailToHead(ListNode listNode){
ArrayList<Integer> lists = new ArrayList<Integer>();
Stack<Integer> stack = new Stack<Integer>();
while(listNode != null){
stack.push(listNode.val);listNode = listNode.next;
}
while(!stack.isEmpty()){
lists.add(stack.pop());
}
return lists;
}
public static void main(String[] args){
ListNode root = new ListNode(1);
root.next = new ListNode(2);
root.next.next = new ListNode(3);
ArrayList<Integer> result = printListFromTailToHead(root);
for(int i=0;i < result.size();i++ ){
System.out.print(result.get(i)+"\t");
}
System.out.println();
}
}

View File

@ -0,0 +1,23 @@
# 剑指offer面试题目
## 简述
**梅花香自苦寒来,宝剑锋从磨砺出。**
## 面试题3
### 题目
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,
输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。<br>
**实现方式:** [java实现](https://github.com/lzh984294471/job/tree/master/java/com/thinker/offer/Offer_3.java)
## 面试题10
### 题目
请实现一个函数输入一个整数输出给数在二进制表示中1的个数。例如把9表示成二进制是1001有2位是1。因此
如果输入9该函数输出2。<br>
**实现方式:** [java实现](https://github.com/lzh984294471/job/tree/master/java/com/thinker/offer/Offer_10.java)
## 面试题11
### 题目
实现函数double power(int expo,int base)求base的expo次方不得使用库函数同时不需要考虑大数的问题。<br>
**实现方式:** [java](https://github.com/lzh984294471/job/tree/master/java/com/thinker/offer/Offer_11.java)
和[c语言实现](https://github.com/lzh984294471/job/tree/master/c/sources/offer/offer11.c)

View File

@ -0,0 +1,40 @@
package com.thinker.bishi.offer;
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){ val = x;}
}
public class ReconstructBinaryTree{
public static TreeNode reConstructBinaryTree(int [] pre,int [] in) {
TreeNode root=reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);
return root;
}
private static TreeNode reConstructBinaryTree(int [] pre,int startPre,int endPre,int [] in,int startIn,int endIn) {
if(startPre>endPre||startIn>endIn)
return null;
TreeNode root=new TreeNode(pre[startPre]);
for(int i=startIn;i<=endIn;i++){
if(in[i]==pre[startPre]){
root.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);
root.right=reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn);
}
}
return root;
}
public static void main(String[] args){
int[] pre = new int[]{1,2,4,7,3,5,6,8};
int[] in = new int[]{4,7,2,1,5,3,8,6};
TreeNode result = reConstructBinaryTree(pre,in);
System.out.println(result);
}
}

View File

@ -0,0 +1,41 @@
package com.thinker.bishi.offer;
public class ReplaceSpace{
public static String replaceSpace(StringBuffer str){
if(str == null) return null;
StringBuilder tmp = new StringBuilder();
for(int i = 0;i<str.length();i++){
if(str.charAt(i) == ' ') tmp.append("%").append("2").append("0");
else tmp.append(str.charAt(i));
}
return tmp.toString();
}
public static String go(StringBuffer str){
if(str == null) return null;
int space = 0;
for(int i = 0;i < str.length();i++){
if(str.charAt(i) == ' ') space ++;
}
int newLength = str.length() + space * 2;
char[] chars = new char[newLength];
int j = newLength - 1;
for(int i = str.length() - 1;i>= 0;i--){
if(str.charAt(i) == ' ') {
chars[j] = '0';chars[j-1] = '2';chars[j-2] = '%'; j -= 3;
}else{
chars[j] = str.charAt(i); j--;
}
}
return new String(chars);
}
public static void main(String[] args){
StringBuffer str = new StringBuffer("We Are Happy");
System.out.println(go(str));
}
}

View File

@ -0,0 +1,67 @@
package com.thinker.bishi.other;
import java.util.*;
/**
* @author lzh
*/
public class Main {
private static int last = 0;
private static List<Integer> tmp = new ArrayList<Integer>();
private static List<Integer> result ;
private static Map<Integer,int[]> tmps = new HashMap<>();
private static int check(int sum,int[] lines,int[] init){
boolean flag = lines[1] <= init[1] && lines[0] == last;
if(flag){
sum += lines[2];
last = lines[1];
tmp.add(last);
}
return sum;
}
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
String[] first = in.nextLine().split(" ");
int[] init = new int[2];
int sum = 0;
int index = 1;
for(int i=0;i<2;i++){
init[i] = Integer.parseInt(first[i]);
}
last = init[0];
tmp.add(last);
while (in.hasNextLine()){
String[] lines = in.nextLine().split(" ");
int[] linesInt = new int[3];
for(int i=0;i<3;i++){
linesInt[i] = Integer.parseInt(lines[i]);
}
tmps.put(index,linesInt);
index += 1;
}
int min = 0;
for(int i=0;i<index;i++){
int[] ints = new int[index];
for(int k=0;k<index;k++){ ints[k] = 0;}
for(int j=0;j<index;j++){
int random = (int)(Math.random()*(10-1));
while (ints[random] == 1){random = (int)(Math.random()*(10-1));}
sum = check(sum,tmps.get(random),init);
}
if(i == 0) min = sum;
else if(sum < min){
result = tmp;
}
}
for(int i=0;i<result.size();i++){
if(i == result.size()-1){
System.out.print(result.get(i)+"("+min+")");
}else {
System.out.print(result.get(i)+"->");
}
}
}
}

View File

@ -0,0 +1,37 @@
package com.thinker.bishi.other;
import java.util.Scanner;
public class StringRotation{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String str = in.nextLine();
String[] strs = str.split(",");
str = strs[0].substring(1,strs[0].length()-1);
int len = Integer.parseInt(strs[1]);
int loca = Integer.parseInt(strs[2]);
StringRotation s = new StringRotation();
System.out.println(s.rotateString(str,len,loca));
}
public String rotateString(String A, int n, int p){
char[] a = A.toCharArray();
rotate(a,0,p);
rotate(a,p+1,n-1);
rotate(a,0,n-1);
return new String(a);
}
public void rotate(char[] a, int begin, int end){
while(begin <= end){
char tmp = a[begin];
a[begin] = a[end];
a[end] = tmp;
begin ++;
end --;
}
}
}

View File

@ -0,0 +1,48 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* @author lzh
*/
public class Main {
private static int last = 0;
private static List<Integer> tmp = new ArrayList<Integer>();
private static int check(int sum,int[] lines,int[] init){
boolean flag = lines[1] <= init[1] && lines[0] == last;
if(flag){
sum += lines[2];
last = lines[1];
tmp.add(last);
}
return sum;
}
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
String[] first = in.nextLine().split(" ");
int[] init = new int[2];
int sum = 0;
for(int i=0;i<2;i++){
init[i] = Integer.parseInt(first[i]);
}
last = init[0];
tmp.add(last);
while (in.hasNextLine()){
String[] lines = in.nextLine().split(" ");
int[] linesInt = new int[3];
for(int i=0;i<3;i++){
linesInt[i] = Integer.parseInt(lines[i]);
}
sum = check(sum,linesInt,init);
}
for(int i=0;i<tmp.size();i++){
if(i == tmp.size()-1){
System.out.print(tmp.get(i)+"("+sum+")");
}else {
System.out.print(tmp.get(i)+"->");
}
}
}
}

View File

@ -0,0 +1,5 @@
/**
* @author lzh
* <p>面试题练习</p>
*/
package com.thinker.bishi;

View File

@ -0,0 +1,39 @@
package com.thinker.bishi.quNaEr;
import java.util.Arrays;
import java.util.Scanner;
/**
* @author lzh
*/
public class Main {
private static int main(int arr[], int sum) {
int count = 0;
if (arr[0] > sum) {
return -1;
}
for (int i = arr.length - 1; i >= 0; i--) {
if(arr[i] <= sum){
sum -= arr[i];
if (sum >= 0) {
count++;
}
else
break;
}
}
return count;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] tmp = sc.nextLine().split(" ");
int[] arr = new int[tmp.length - 1];
int sum = Integer.parseInt(tmp[tmp.length - 1]);
for (int i = 0; i < arr.length; i++) arr[i] = Integer.parseInt(tmp[i]);
Arrays.sort(arr);
System.out.println(main(arr, sum));
}
}

View File

@ -0,0 +1,28 @@
package com.thinker.bishi.saima;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
/**
* @author lzh
* <p href="http://exercise.acmcoder.com/online/online_judge_ques?ques_id=1649&konwledgeId=134">
* http://exercise.acmcoder.com/online/online_judge_ques?ques_id=1649&konwledgeId=134
* </p>
*/
public class DiffDate {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
Date date = df.parse(sc.nextLine());
Date now = df.parse("2015-10-18");
long l = date.getTime() - now.getTime();
long day = l / (24 * 60 * 60 * 1000);
System.out.println(day);
}
}

View File

@ -0,0 +1,22 @@
package com.thinker.bishi.saima;
import java.util.Scanner;
/**
* @author lzh
*/
public class JiGuChuanHua {
private static int count = 0;
private static void chuanHua(int curr){
}
private static void main(){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
}
public static void main(String[] args) {
main();
}
}

View File

@ -0,0 +1,53 @@
package com.thinker.bishi.saima;
import java.util.Scanner;
/**
* @author lzh
* <p href="http://exercise.acmcoder.com/online/online_judge_ques?ques_id=1656&konwledgeId=134">
* http://exercise.acmcoder.com/online/online_judge_ques?ques_id=1656&konwledgeId=134
* </p>
*/
public class OverTurnArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int len = in.nextInt();
int[] arr = new int[len];
for(int i=0;i<len;i++){
arr[i] = in.nextInt();
}
getOverturn(arr,len);
}
private static void getOverturn(int[] arr,int len){
int begin = 0,end = 0;
boolean flag = false;
//find begin and end
for(int i=0;i<len-1;i++){
if(!flag && arr[i] > arr[i+1]){
begin = i;flag = true;
}else if(flag && arr[i] < arr[i+1]){
end = i;break;
}
}
while (begin < end && begin >= 0 && end <=len-1){
int tmp = arr[begin];
arr[begin] = arr[end];
arr[end] = tmp;
begin ++;end--;
}
flag = true;
for(int i=0;i<len-1;i++){
if(arr[i] > arr[i+1]){
flag = false;
}
}
if(flag){
System.out.println("yes");
}else {
System.out.println("no");
}
}
}

View File

@ -0,0 +1,45 @@
package com.thinker.bishi.saima;
import java.util.Scanner;
/**
* @author lzh
* @apiNote 题目描述:
* <p href="http://exercise.acmcoder.com/online/online_judge_ques?ques_id=1667&konwledgeId=134">
* http://exercise.acmcoder.com/online/online_judge_ques?ques_id=1667&konwledgeId=134
* </p>
*
*/
public class PassWord {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int l = in.nextInt();
int r = in.nextInt();
int m = in.nextInt();
if(l>r){
System.out.println(-1);
return;
}
int count = 0;
for(int i=l;i<=r;i++){
if(check(i,m)) count ++;
}
if(count == 0){
System.out.println(-1);
}else {
System.out.println(count);
}
}
private static boolean check(int n,int m){
while(n != 0){
if((n&1) == 1) m--;
n = n >> 1;
}
if(m == 0){
return true;
}
return false;
}
}

View File

@ -0,0 +1,41 @@
package com.thinker.bishi.saima;
import java.util.Scanner;
/**
* @author lzh
* <p href="http://exercise.acmcoder.com/online/online_judge_ques?ques_id=1668&konwledgeId=134">
* http://exercise.acmcoder.com/online/online_judge_ques?ques_id=1668&konwledgeId=134
* </p>
*/
public class Stairs {
private static int count = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
if(n <= 0) return;
for(int i=0;i<n;i++){
int m = in.nextInt();
result(m);
System.out.println(count);
count = 0;
}
}
private static void result(int m){
go(m,1);
go(m,2);
}
private static void go(int m,int step){
if(m <= 1 || m <= step){
if(m == 1 && m == step){
count ++;
}
return;
}
m -= step;
go(m,1);
go(m,2);
}
}

View File

@ -0,0 +1,36 @@
package com.thinker.bishi.saima;
import java.util.Arrays;
import java.util.Scanner;
/**
* @author lzh
* <p href="http://exercise.acmcoder.com/online/online_judge_ques?ques_id=1500&konwledgeId=134">
* http://exercise.acmcoder.com/online/online_judge_ques?ques_id=1500&konwledgeId=134
* </p>
*
*/
public class StreetLamp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int len = in.nextInt();
int[] lamp = new int[num];
for(int i=0;i<num;i++){
lamp[i] = in.nextInt();
}
Arrays.sort(lamp);
double max = Double.MIN_VALUE;
for(int i=1;i<num;i++){
double diff = lamp[i] - lamp[i-1];
if(diff > max){
max = diff;
}
}
double left = lamp[0];
double right = len - lamp[num-1];
if(left>right && left>max/2) System.out.printf("%.2f",left);
if(right>left && right>max/2) System.out.printf("%.2f",right);
else System.out.printf("%.2f",max/2);
}
}

View File

@ -0,0 +1,24 @@
package com.thinker.bishi.saima;
/**
* @author lzh
*/
public class Test {
private static int count = 0;
private static void jump(int num,int jump){
if((num - jump) > 0) count += jump;
else return;
num -= jump;
jump(num, 1);
jump(num, 2);
}
private static int jump(int num){
jump(num ,1);
jump(num , 2);
return count;
}
public static void main(String[] args) {
System.out.println(jump(3));
}
}

View File

@ -0,0 +1,49 @@
package com.thinker.bishi.saima;
import java.util.LinkedList;
import java.util.Scanner;
/**
* @author lzh
*/
public class Test2 {
private LinkedList<Character> base = new LinkedList<>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String[] strings = new String[n];
for (int i = 0; i < n; i++){
strings[i] = in.next();
}
for(int i=0;i < n;i++) {
Test2 mainn = new Test2("abcdefghijkl");
System.out.println(mainn.rankString(strings[i]));
}
}
public Test2(String s){
char[] chars = s.toCharArray();
int n = chars.length;
for(int i = 0; i < n ; i++){
base.add(chars[i]);
}
}
public int rankString(String target){
int rank = 1;
int size = base.size();
for(int i = 0; i<size;i++){
int locOfIthChar =base.indexOf(target.charAt(i));
base.remove(locOfIthChar);
rank += locOfIthChar*factorial(size-i-1);
}
return rank;
}
private int factorial(int n){
int ans = 1;
for(int i = 1 ; i<=n;i++){
ans*= i;
}
return ans;
}
}

View File

@ -0,0 +1,45 @@
package com.thinker.bishi.saima;
import java.util.Scanner;
/**
* @author lzh
* <p href="http://exercise.acmcoder.com/online/online_judge_ques?ques_id=1677&konwledgeId=134">
* http://exercise.acmcoder.com/online/online_judge_ques?ques_id=1677&konwledgeId=134
* </p>
*
*/
public class YueDeEr {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String firstLine = in.nextLine();
String secondLine = in.nextLine();
firstLine = change(firstLine);
System.out.printf("%.2f%%",check(firstLine.toCharArray(),secondLine.toCharArray()));
}
private static double check(char[] firstLine,char[] secondLine){
double result = firstLine.length;
int count = 0;
for(int i=0;i<firstLine.length;i++){
if(firstLine[i] == secondLine[i])
count ++;
}
result = count*100/result;
return result;
}
private static String change(String firstLine){
char[] tmps = firstLine.toCharArray();
for(int i=0;i<firstLine.length();i++){
int tmp = (int)tmps[i];
if((tmp >=48 && tmp <= 57) || (tmp >=65 && tmp <= 90) || (tmp >=97 && tmp <= 122)){
tmps[i] = (char)(1+48);
}else {
tmps[i] = (char)(48);
}
}
return new String(tmps);
}
}

View File

@ -0,0 +1,31 @@
package com.thinker.bishi.toutiao;
import java.util.Scanner;
/**
* @author lzh
*/
public class Main1 {
private static int[] changeToArray(String[] strArray, int len) {
int[] arr = new int[len];
for (int i = 0; i < len; i++) {
arr[i] = Integer.parseInt(strArray[i]);
}
return arr;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int len = Integer.parseInt(in.nextLine());
String[] strArr = in.nextLine().split(" ");
int[] arr = changeToArray(strArr,len);
int count = 0;
for(int i=0;i<len;i++){
for(int j=i+1;j<len;j++){
if(Math.abs((arr[i] - arr[j])) <= 10){count ++;}
}
}
System.out.println(count);
}
}

View File

@ -0,0 +1,30 @@
package com.thinker.bishi.toutiao;
import java.util.Scanner;
/**
* @author lzh
*/
public class Main2 {
private void main(){
Scanner in = new Scanner(System.in);
int len = in.nextInt(),m = in.nextInt();
int count = 0;
int[] arr = new int[len];
while(count < len){
arr[count] = in.nextInt();
count ++;
}
count = 0;
for(int i=0;i<len-1;i++){
for(int j=i+1;j<len;j++){
if((arr[i] ^ arr[j]) > m) count ++;
}
}
System.out.println(count);
}
public static void main(String[] args) {
Main2 main2 = new Main2();
main2.main();
}
}

View File

@ -0,0 +1,27 @@
package com.thinker.bishi.toutiao;
import java.util.Scanner;
public class Main3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int max = sc.nextInt();
int k = sc.nextInt();
int i=1,j=0,count = 0,result = 0,curr=i;
int tmp = 0;
while (count<k){
while (i*10<(j*10+i-tmp) && i*10 <= max){
result = i*10;count++;i++;
if(count>=k) break;
}
while (i*10>(j*10+i) && (j*10+i-1)<=max){
result = j*10+i-1;j++;count++;
if(count>=k) break;
}
if(i*10>max && (j*10-curr) > max){curr ++;}
if(i*10>max || (j*10+curr)>max){j=0;curr = i;}
}
System.out.println(result);
}
}

View File

@ -0,0 +1,10 @@
package com.thinker.bishi.works;
/**
* @author lzh
*/
public class Main2 {
public static void main(String[] args) {
}
}

View File

@ -0,0 +1,38 @@
package com.thinker.bishi.xiaomi;
/**
* @author lzh
*/
public class Binary {
public int countBitDiff(int m, int n) {
int count = 0;
int len = 32;
while (len >= 0){
if((1 & n) != (1 & m)) count ++;
n >>= 1;m >>= 1;len --;
}
return count;
}
public char findFirstRepeat(String A, int n) {
// write code here
char result = ' ';
boolean flag = false;
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
if(A.charAt(i) == A.charAt(j)){
result = A.charAt(i);
flag = true;
break;
}
}
if(flag) break;
}
return result;
}
public static void main(String[] args) {
Binary binary = new Binary();
System.out.println(binary.findFirstRepeat("kdbaaak",7));
}
}

View File

@ -0,0 +1,44 @@
package com.thinker.bishi.xiaomi;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* @author lzh
*/
public class FenSheng {
private static int len = 10;
private static String[] key = new String[]{"ZERO", "ONE", "TWO", "THREE", "FOUR",
"FIVE", "SIX", "SEVEN", "EIGHT", "NINE"};
private static int[] model = new int[len];
private static void init(){
for (int i=0;i<len;i++){
model[(i+8)%10] = i;
}
}
public static void main(String[] args) {
init();
Scanner in = new Scanner(System.in);
int size = Integer.parseInt(in.nextLine());
while (size > 0){
String tmp = in.nextLine();
while (tmp != null){
for(int i=0;i<len;i++){
int index = tmp.indexOf(key[i]);
if(index != -1) {
System.out.print(model[i]);
if(tmp.length() == key[i].length()){
tmp = null;
break;
}else {
tmp = tmp.substring(key[i].length());
}
}
}
}
size--;
System.out.println();
}
}
}

View File

@ -0,0 +1,17 @@
package com.thinker.bishi.xiaomi;
import java.util.Scanner;
/**
* @author lzh
*/
public class JuziFanZhuan {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[] strIn = in.nextLine().split(" ");
for(int i=strIn.length-1;i>=0;i--){
System.out.print(strIn[i]+" ");
}
}
}

View File

@ -0,0 +1,31 @@
package com.thinker.bishi.xiaomi;
import java.util.Scanner;
public class NiuShi{
private static int in = 2;
private static int out = 1;
public static void main(String[] args){
Scanner ins = new Scanner(System.in);
String str = ins.nextLine();
String[] strs = str.split(",");
int[] prices = new int[strs.length];
for(int i=0;i<prices.length;i++){
prices[i] = Integer.parseInt(strs[i]);
}
NiuShi niuShi = new NiuShi();
niuShi.calculateMax(prices);
}
public int calculateMax(int[] prices){
return 0;
}
public void go(int[] prices, int i){
}
}

View File

@ -0,0 +1,44 @@
package com.thinker.bishi.xiaomi;
import java.util.Scanner;
/**
* @author lzh
*/
public class ShuGao {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int len = Integer.parseInt(in.nextLine());
int[][] arr = new int[len][len];
for(int i=0;i<len;i++){
for(int j=0;j<len;j++){
arr[i][j] = 0;
}
}
arr[0][0] = 1;
int k=1;
while (k<len){
String[] tmp = in.nextLine().split(" ");
int i = Integer.parseInt(tmp[0])+1;
int j = Integer.parseInt(tmp[1]);
arr[i][j] = 1;
k++;
}
k = 0;
for(int i=0;i<len;i++){
int count = 0;
for(int j=0;j<len;j++){
if(arr[i][j] == 1){
k++;
break;
}else {
count ++;
}
}
if(count == len){
break;
}
}
System.out.println(k);
}
}

View File

@ -0,0 +1,12 @@
package com.thinker.bishi.xiaomi;
/**
* Created by lzh on 9/23/16.
*/
public class Test {
public static void main(String[] args) {
for(int i=0;i<10;i++){
System.out.println((i+8)%10);
}
}
}

View File

@ -0,0 +1,20 @@
package com.thinker.common;
import java.util.Scanner;
/**
* @author lzh
*/
public class Main {
public static void main(String args[])
{
Scanner cin = new Scanner(System.in);
int a, b;
while(cin.hasNextInt())
{
a = cin.nextInt();
b = cin.nextInt();
System.out.println(a + b);
}
}
}

View File

@ -0,0 +1,6 @@
# java基础
##
## java io 流
- PipedInputStream、PipedOutputStream 实现线程之间的通信
-

View File

@ -0,0 +1,43 @@
package com.thinker.common.classloader;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandlerFactory;
/**
* @author lzh
*/
public class HotSwapClassLoader extends URLClassLoader {
public HotSwapClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}
public HotSwapClassLoader(URL[] urls) {
super(urls);
}
public HotSwapClassLoader(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) {
super(urls, parent, factory);
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
return loadClass(name,false);
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
if(null != super.findLoadedClass(name)) reload(name, resolve);
Class<?> clazz = super.findClass(name);
if(resolve) super.resolveClass(clazz);
return clazz;
}
public Class<?> reload(String name ,boolean resolve) throws ClassNotFoundException{
return new HotSwapClassLoader(super.getURLs(), super.getParent()).loadClass(name, resolve);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
return super.findClass(name);
}
}

View File

View File

@ -0,0 +1,69 @@
package com.thinker.common.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class NioClient{
//通道管理器
private Selector selector;
public NioClient init(String ip, int port) throws IOException{
//获取socket通道
SocketChannel channel = SocketChannel.open();
channel.configureBlocking(false);
//获取通道管理器
selector = Selector.open();
channel.connect(new InetSocketAddress(ip, port));
channel.register(selector, SelectionKey.OP_CONNECT);
return this;
}
public void listen() throws IOException{
System.out.println("client start");
//轮询访问selector
while(true){
//选择注册过io的事件(第一次为SelectionKey.OP_CONNECT)
selector.select();
Iterator<SelectionKey> ite = selector.selectedKeys().iterator();
while(ite.hasNext()){
SelectionKey key = ite.next();
ite.remove();
if(key.isConnectable()){
SocketChannel channel = (SocketChannel)key.channel();
if(channel.isConnectionPending()){
channel.finishConnect();
}
channel.configureBlocking(false);
//send message to service
channel.write(ByteBuffer.wrap(new String("send message to service").getBytes()));
channel.register(selector, SelectionKey.OP_READ);
System.out.println("client connect success");
}else if(key.isReadable()){//read message
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);
byte[] data = buffer.array();
String message = new String(data);
System.out.println("receive message size:"+buffer.position()+"\tmessage:"+message);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
break;
}
channel.write(ByteBuffer.wrap(new String("hello ,service").getBytes()));
}
}
}
}
public static void main(String[] args) throws IOException{
new NioClient().init("127.0.0.1",1994).listen();
}
}

View File

@ -0,0 +1,85 @@
package com.thinker.common.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
/**
* nio nio different from bio nio
*
* */
public class NioServer{
private Selector selector;
/**
*
* @param port 监听端口
* 初始化服务器
*
* */
private NioServer init(int port) throws IOException{
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.bind(new InetSocketAddress(port));
selector = Selector.open();
//将通道管理器与通道绑定并为该通道注册SelectionKey.OP_ACCEPT事件
//只有当该事件到达时Select.select()会返回否则一直阻塞
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
return this;
}
public void listen() throws IOException{
System.out.println("service starting.....");
while(true){
//当有注册事件到达时方法返回否则阻塞
selector.select();
//获取selector中的迭代器选中项为注册的事件
Iterator<SelectionKey> ite = selector.selectedKeys().iterator();
while(ite.hasNext()){
SelectionKey key = ite.next();
//删除已选key防止重复处理
ite.remove();
//客户端连接事件
if(key.isAcceptable()){
ServerSocketChannel server = (ServerSocketChannel)key.channel();
//获取客户端连接通道
SocketChannel channel = server.accept();
channel.configureBlocking(false);
channel.write(ByteBuffer.wrap(new String("send to client").getBytes()));
channel.register(selector, SelectionKey.OP_READ);
System.out.println("client connect");
}else if(key.isReadable()){//有可读数据事件
//获取客户端传输数据可读消息通道
SocketChannel channel = (SocketChannel)key.channel();
//创建读取数据缓存器
ByteBuffer buffer = ByteBuffer.allocate(1024);
int read = channel.read(buffer);
byte[] data = buffer.array();
String message = new String(data);
System.out.println("receive message from client, size:"+buffer.position()+"\tmessage:"+message);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
break;
}
ByteBuffer out = ByteBuffer.wrap(new String("hello world").getBytes());
channel.write(out);
}
}
}
}
public static void main(String[] args) {
try{
new NioServer().init(1994).listen();
}catch(IOException e){
e.printStackTrace();
System.exit(0);
}
}
}

View File

@ -0,0 +1,5 @@
/**
* @author lzh
* <p>简单的Java demo</p>
*/
package com.thinker.common;

View File

@ -0,0 +1,8 @@
package com.thinker.common.proxy;
/**
* Created by lzh on 8/3/16.
*/
public interface Father {
void say();
}

View File

@ -0,0 +1,13 @@
package com.thinker.common.proxy;
/**
* Created by lzh on 8/3/16.
* 实现类
*
*/
public class FatherImpl implements Father{
@Override
public void say() {
System.out.println("Hello world");
}
}

View File

@ -0,0 +1,29 @@
package com.thinker.common.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* Created by lzh on 8/3/16.
* 利用反射调用实现类的方法实现动态代理
*
*/
public class Handler<T> implements InvocationHandler {
private Class<T> t;
public Handler(Class<T> t){
this.t = t;
}
private void before(){
System.out.println("before");
}
private void after(){
System.out.println("after");
}
@Override
public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
this.before();
Object object = method.invoke(t.newInstance(),args);
this.after();
return object;
}
}

View File

@ -0,0 +1,28 @@
package com.thinker.common.proxy;
import java.lang.reflect.Proxy;
/**
* Created by lzh on 8/3/16.
* 练习动态代理的使用
*
*/
public class TestDynamicProxy {
private static void dynamicProxy() throws IllegalAccessException, InstantiationException {
Handler log = new Handler<>(FatherImpl.class);
Father proxy = (Father) Proxy.newProxyInstance(Father.class.getClassLoader(),
FatherImpl.class.getInterfaces(),log);
proxy.say();
}
public static void main(String[] args) {
try {
dynamicProxy();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,13 @@
package com.thinker.common.test;
import java.util.HashMap;
import java.util.Map;
public class Test{
public static void main(String[] args) {
System.out.println((char) ('B'+32)+"\t");
Map<String,Object> map = new HashMap<>();
map.put("hh","");
}
}

Some files were not shown because too many files have changed in this diff Show More