0%

查询所有记录中搜索频次最高的30个关键词

主要分两个步骤,首先多个mapper分别处理所有数据中的一部分关键词数据,然后汇总到reducer做词频统计。

CountWordMapper

在Mapper中处理每一小块数据,使用HashMap存储关键字及其频次,可以节省时间,key为查询的关键字。Mapper返回一个<Text , LongWritable>的列表,存储当前文件块中的关键字及其频次,传给reducer作统计。

CountWordReducer

Reducer将所有mapper得到的关键字及频次汇总,不同mapper下的相同关键字在此合并,可得到当前关键字的总频次。为了得到TopK数据,在reducer维护一个大小为K的小顶堆,每次得到一个关键词的搜索总频次即向堆中插入一个Pair<String, Long>,堆中元素排序自定义为关键词频次Long。当堆元素个数大于K时,将堆顶元素(即当前最小元素,第K大的元素)删除。最后reducer可得到访问频次最大的TopK关键词。输出前将堆中元素按频次排序即可。

词频统计完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
//Main.java
public class Main {
    public static void main(String[] args) throws Exception {
        countWords();    //统计词频前30的搜索关键词
        countUrls();   //被访问次数前10的网址及其次数占比
    }

    private static void countWords() throws Exception {
        String input_dir = "./data/sogou.full.utf8";//input
        String outputDir = "./result/words";//output

        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(conf);
        fs.deleteOnExit(new Path(outputDir));
        fs.close();

        Job job = new Job(conf, "CountWords");
        job.setMapperClass(CountWordMapper.class);
        job.setReducerClass(CountWordReducer.class);
       
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        job.setInputFormatClass(TextInputFormat.class);
        TextInputFormat.setInputPaths(job, new Path(input_dir));

        job.setOutputFormatClass(TextOutputFormat.class);
        TextOutputFormat.setOutputPath(job, new Path(outputDir));
        job.waitForCompletion(true);

    }

}

//CountWordMapper.java
public class CountWordMapper extends Mapper<LongWritable, Text, Text, LongWritable> {
    //使用hash表存储关键词和该词的频次
    HashMap<String, Long> map = new HashMap<>();

    @Override
    public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

        //分离各项数据,以‘\t’为间隔标志
        String fields[] = value.toString().split("\t");

        if (fields.length != 6) {
            return;
        }
        String keyWord = fields[2];

        long count=map.getOrDefault(keyWord,-1L);
        if (count==-1L)//判断该词是否已存在于hash表中
            map.put(keyWord,1L);//不存在,加入新词
        else
            map.replace(keyWord,count+1);//存在,词频加一
    }

    @Override
    protected void cleanup(Mapper<LongWritable, Text,  Text , LongWritable>.Context context) throws IOException, InterruptedException {
        //将当前文件块内关键词的频度输出给reducer
        for (String keyWord : map.keySet()) {
            context.write(new Text(keyWord), new LongWritable(map.get(keyWord)));
        }
    }
}


//CountWordReducer.java
public class CountWordReducer extends Reducer<Text, LongWritable, Text, LongWritable> {
    public static int K = 30;//选出频次最大的K条关键词

    //小顶堆,容量K,用于快速删除词频最小的元素
    PriorityQueue<Pair<String, Long>> minHeap = new PriorityQueue<>((p1, p2) -> (int) (p1.getValue() - p2.getValue()));

    //每次传入的参数为key相同的values的集合
    public void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
        long total = 0;
        for (LongWritable count : values) {
            //依次取出每个mapper统计的关键词key的频次,加起来
            total += count.get();
        }

        Pair<String, Long> tmp = new Pair<>(key.toString(), total);
        minHeap.add(tmp);//向小顶堆插入新的关键词词频
        if (minHeap.size() > K)//若小顶堆容量达到要求的上限
            minHeap.poll();//删除堆顶最小的元素,保持TopK
    }

    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        List<Pair<String, Long>> list = new ArrayList<>();
        //从小顶堆中取出数据,便于排序
        for (Pair<String, Long> p : minHeap)
            list.add(p);

        //对搜索词频前K个元素排序
        Collections.sort(list, ((p1, p2) -> (int) (p2.getValue() - p1.getValue())));

        //reducer的输出,按搜索词频排好序的TopK关键词
        for (Pair<String, Long> t : list)
            context.write(new Text(t.getKey()), new LongWritable(t.getValue()));
    }
}

字符流

java的文本(char)是16位无符号整数,是字符的unicode编码(双字节编码).
文件是byte byte byte …的数据序列,文本文件是文本(char)序列按照某种编码方案(utf-8,utf-16be,gbk)序列化为byte的存储结果.

字符流(Reader Writer)—->操作的是文本文件
字符的处理,一次处理一个字符
字符的底层任然是基本的字节序列

字符流的基本实现

InputStreamReader完成byte流到char流,按照编码规则解析
OutputStreamWriter完成char流到byte流,按照编码规则转化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
FileInputStream in = new FileInputStream("e:\\javaio\\utf8.txt");
InputStreamReader isr = new InputStreamReader(in,"utf-8");//默认项目的编码,操作的时候,要写文件本身的编码格式

FileOutputStream out = new FileOutputStream("e:\\javaio\\utf81.txt");
OutputStreamWriter osw = new OutputStreamWriter(out,"utf-8");
char[] buffer = new char[8*1024];
int c;
/*批量读取,放入buffer这个字符数组,从第0个位置开始放置,最多放buffer.length个
返回的是读到的字符的个数
*/
while(( c = isr.read(buffer,0,buffer.length))!=-1){
String s = new String(buffer,0,c);
System.out.print(s);
osw.write(buffer,0,c);
osw.flush();
}
isr.close();
osw.close();

FileReader/FileWriter

进一步封装了文件字符流的读写,使用更方便:

1
2
3
4
5
6
7
8
9
10
11
FileReader fr = new FileReader("e:\\javaio\\demo.txt");
FileWriter fw = new FileWriter("e:\\javaio\\demo2.txt");
//FileWriter fw = new FileWriter("e:\\javaio\\demo2.txt",true);
char[] buffer = new char[2056];
int c ;
while((c = fr.read(buffer,0,buffer.length))!=-1){
fw.write(buffer,0,c);
fw.flush();
}
fr.close();
fw.close();

字符流的过滤器

PrintWriterBufferedWriter使用更方便.
BufferedReader.readLine()一次读一行
BufferedWriter/PrintWriter一次写一行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
	//对文件进行读写操作 
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream("e:\\javaio\\imooc.txt")));
/*BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("e:\\javaio\\imooc3.txt")));*/
PrintWriter pw = new PrintWriter("e:\\javaio\\imooc4.txt");
//PrintWriter pw1 = new PrintWriter(outputStream,boolean autoFlush);
String line ;
while((line = br.readLine())!=null){
System.out.println(line);//一次读一行,并不能识别换行
/*bw.write(line);
//单独写出换行操作
bw.newLine();//换行操作
bw.flush();*/
pw.println(line);
pw.flush();
}
br.close();
//bw.close();
pw.close();

获取Class Type的三种方式

获取

  1. Class c1 = Foo.class;
  2. Class c2 = foo.getClass();
    c1 == c2 -> true 类对象唯一
  3. Class c3 = Class.forName("com.xxx.Foo");
    推荐使用该方式,最快,但会抛异常,要try-catch

使用

1
Foo foo = (Foo)c1.newInstance();//Foo需要有无参构造函数

动态加载类

使用new创建对象,是静态加载类,在编译时刻就需要加载所有可能用到的类。 如果项目中大部分类暂时用不到(比如用于解决特例情况),或者为了避免因一个(模块)类的失效导致整个系统的不可用,我们可以使用动态(运行时)加载类。
如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Excel implements OfficeAble {
public void start() {
System.out.println("Excel starting...")
}
}
class Word implements OfficeAble {
public void start() {
System.out.println("Word starting...")
}
}
class Office {
public static void main(String[] args) {
try {
//动态加载类,在运行时刻加载
Class class = Class.forName(args[0]);
//Foo需要有无参构造函数
OfficeAble oa = (OfficeAble)class.newInstance();
oa.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}

编译好发布以后,后期软件更新,新的模块(如ppt)只需要实现OfficeAble接口即可。

获取Class Type信息

我们可以通过以下代码简单地获取一个类的成员函数成员变量构造函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
public class ClassUtil {
/**
* 打印类的信息,包括类的成员函数、成员变量
* @param obj 该类的一个对象
*/
public static void printClassMethodMessage(Object obj){
//要获取类的信息 首先要获取类的类类型
Class c = obj.getClass();//传递的是哪个子类的对象 c就是该子类的类类型
//获取类的名称
System.out.println("类的名称是:"+c.getName());
/*
* Method类,方法对象
* 一个成员方法就是一个Method对象
* getMethods()方法获取的是所有的public的函数,包括父类继承而来的
* getDeclaredMethods()获取的是所有该类自己声明的方法,不问访问权限
*/
Method[] ms = c.getMethods();//c.getDeclaredMethods()
for(int i = 0; i < ms.length;i++){
//得到方法的返回值类型的类类型
Class returnType = ms[i].getReturnType();
System.out.print(returnType.getName()+" ");
//得到方法的名称
System.out.print(ms[i].getName()+"(");
//获取参数类型--->得到的是参数列表的类型的类类型
Class[] paramTypes = ms[i].getParameterTypes();
for (Class class1 : paramTypes) {
System.out.print(class1.getName()+",");
}
System.out.println(")");
}
}
/**
* 获取成员变量的信息
* @param obj
*/
public static void printFieldMessage(Object obj) {
Class c = obj.getClass();
/*
* 成员变量也是对象
* java.lang.reflect.Field
* Field类封装了关于成员变量的操作
* getFields()方法获取的是所有的public的成员变量的信息
* getDeclaredFields获取的是该类自己声明的成员变量的信息
*/
//Field[] fs = c.getFields();
Field[] fs = c.getDeclaredFields();
for (Field field : fs) {
//得到成员变量的类型的类类型
Class fieldType = field.getType();
String typeName = fieldType.getName();
//得到成员变量的名称
String fieldName = field.getName();
System.out.println(typeName+" "+fieldName);
}
}
/**
* 打印对象的构造函数的信息
* @param obj
*/
public static void printConMessage(Object obj){
Class c = obj.getClass();
/*
* 构造函数也是对象
* java.lang. Constructor中封装了构造函数的信息
* getConstructors获取所有的public的构造函数
* getDeclaredConstructors得到所有的构造函数
*/
//Constructor[] cs = c.getConstructors();
Constructor[] cs = c.getDeclaredConstructors();
for (Constructor constructor : cs) {
System.out.print(constructor.getName()+"(");
//获取构造函数的参数列表--->得到的是参数列表的类类型
Class[] paramTypes = constructor.getParameterTypes();
for (Class class1 : paramTypes) {
System.out.print(class1.getName()+",");
}
System.out.println(")");
}
}
}

方法的反射

方法名称+参数列表 确定一个方法
通过method.invoke();实现反射调用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class MethodDemo {
public static void main(String[] args) {
//要获取print(int ,int )方法 1.要获取一个方法就是获取类的信息,获取类的信息首先要获取类的类类型
A a1 = new A();
Class c = a1.getClass();
/*
* getMethod获取的是public的方法
* getDelcaredMethod自己声明的方法
*/
try {
// Method m = c.getMethod("print", new Class[]{int.class,int.class});
Method m = c.getMethod("print", int.class,int.class);

// 方法的反射操作
// a1.print(10, 20);方法的反射操作是用m对象来进行方法调用 和a1.print调用的效果完全相同
// 方法如果没有返回值返回null,有返回值返回具体的返回值
// Object o = m.invoke(a1,new Object[]{10,20});
Object o = m.invoke(a1, 10,20);
System.out.println("==================");
// 获取方法print(String,String)
Method m1 = c.getMethod("print",String.class,String.class);
// 用方法进行反射操作
// a1.print("hello", "WORLD");
o = m1.invoke(a1, "hello","WORLD");
System.out.println("===================");
// Method m2 = c.getMethod("print", new Class[]{});
Method m2 = c.getMethod("print");
// m2.invoke(a1, new Object[]{});
m2.invoke(a1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class A{
public void print(){
System.out.println("helloworld");
}
public void print(int a,int b){
System.out.println(a+b);
}
public void print(String a,String b){
System.out.println(a.toUpperCase()+","+b.toLowerCase());
}
}

帮助理解泛型的本质

Java中集合的泛型,定义的模板是防止错误输入的,只在编译阶段有效,编译阶段以后就无效了,我们可以通过方法的反射来操作,绕过泛型模板的限制。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class MethodDemo {
public static void main(String[] args) {
ArrayList list = new ArrayList();

ArrayList<String> list1 = new ArrayList<String>();
list1.add("hello");
//list1.add(20);错误的
Class c1 = list.getClass();
Class c2 = list1.getClass();
System.out.println(c1 == c2);
//反射的操作都是编译之后的操作,c1==c2结果返回true说明编译之后集合的泛型是去泛型化的, 验证:我们可以通过方法的反射来操作,绕过编译
try {
Method m = c2.getMethod("add", Object.class);
m.invoke(list1, 20);//绕过编译操作就绕过了泛型
System.out.println(list1.size());
System.out.println(list1);
/*for (String string : list1) {
System.out.println(string);
}*///现在不能这样遍历
} catch (Exception e) {
e.printStackTrace();
}
}
}

文件的编码

文本文件就是字符(字节)序列,是原始字符串按照某种编码方式编码而成的字节序列.常见编码有

  • utf-8 中文3字节 英文1字节
  • ansi 扩展的ASCII编码 中文2字节 英文1字节
  • GBK 中文系统下,ansi即GBK,是基于GB2312的扩展 中文2字节 英文1字节
  • utf-16be java双字节编码 中文2字节 英文2字节
1
2
3
4
5
6
7
8
9
10
String s="中文abc";
byte[] bytes=s.getBytes("gbk");
//byte[] bytes=s.getBytes("utf-8");
for(byte b:bytes){//int 4 byte
System.out..println(Integer.toHexString(b & 0xff) + " ");
}

String str=new String(bytes,"utf-8");
System.out..println(str);//输出乱码,因为bytes是按gbk编码的
//String str=new String(bytes,"gbk");

File类

java.io.File类用于表示文件和目录,但不能访问文件的内容,用法示例:

1
2
3
file.getAbsolutePath();
file.getName();
file.getParent();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public static void main(String[] args) {
// 了解构造函数的情况 查帮助
File file = new File("E:\\javaio\\imooc");
//System.out.println(file.exists());
if(!file.exists())
file.mkdir(); //file.mkdirs()多级目录
else
file.delete();
//是否是一个目录 如果是目录返回true,如果不是目录or目录不存在返回的是false
System.out.println(file.isDirectory());
//是否是一个文件
System.out.println(file.isFile());

//File file2 = new File("e:\\javaio\\日记1.txt");
File file2 = new File("e:\\javaio","日记1.txt");
if(!file2.exists())
try {
file2.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
else
file2.delete();
//常用的File对象的API
System.out.println(file);//file.toString()的内容
System.out.println(file.getParentFile().getAbsolutePath());
}

RandomAccessFile类

提供对文件内容的访问,支持随机读写文件.文件读写完毕应关闭close().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
```writeInt()```写int 4个字节
```read()```一次只读一个字节
```getFilePointer()```获取文件指针
```seek()```移动文件指针
```java
public class RandomAccessFileSeriaDemo {
public static void main(String[] args)throws IOException {
File demo = new File("demo1");
if (!demo.exists()) demo.mkdir();
File file = new File(demo, "raf.dat");
if (!file.exists())
file.createNewFile();
//打开文件,进行随机读写
RandomAccessFile raf = new RandomAccessFile(file, "rw");
/*序列化*/
//写int 4 byte
int i = 0x7ffffff;
raf.write(i >>> 24);//右移24位 写高8位
raf.write(i >>> 16);
raf.write(i >>> 8);
raf.write(i);
// raf.writeInt(i);
System.out.println(raf.getFilePointer());
}
}

IO流(输入流,输出流)

字节流

InputStream

读一字节填充到int低8位:
int b = in.read();
读数据填充到字节数组:
in.read(byte[] buf);
in.read(byte[] buf,int start,int size);

OutputStream

写int的低8位写入到流:
out.write(int b)
将字节数组写入到流:
out.write(byte[] buf);
out.write(byte[] buf,int start,int size);

FileInputStream

FileInputStream是InputStream的子类
把文件作为字节流进行读操作
读取指定文件内容,按照16进制输出到控制台
每输出10个byte换行
单字节读取不适合大文件,大文件效率很低

1
2
3
4
5
6
7
8
9
10
11
12
13
14
FileInputStream in = new FileInputStream(fileName);
int b ;//存储每次读到的一个字节
int i = 1;
while((b = in.read())!=-1){
if(b <= 0xf){
//单位数前面补0
System.out.print("0");
}
System.out.print(Integer.toHexString(b)+" ");
if(i++%10==0){
System.out.println();
}
}
in.close();

批量读取文件并输出,对大文件而言效率高:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
   FileInputStream in = new FileInputStream(fileName);
byte[] buf = new byte[8 * 1024];
int bytes = 0;//读到的字节的个数
int j = 1;
//一次可能读不满,只要读到数据,bytes就不可能是-1
while((bytes = in.read(buf,0,buf.length))!=-1){
for(int i = 0 ; i < bytes;i++){
System.out.print(Integer.toHexString(buf[i] & 0xff)+" ");
if(j++%10==0){
System.out.println();
}
}
}
in.close();

FileOutputStream

FileOutputStream是OutputStream的子类
将字节流写入文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//如果该文件不存在,则直接创建,如果存在,删除后创建
FileOutputStream out = new FileOutputStream("demo/out.dat");
out.write('A');//写出了'A'的低八位
out.write('B');//写出了'B'的低八位
int a = 10;//write只能写八位,那么写一个int需要些4次每次8位
out.write(a >>> 24);
out.write(a >>> 16);
out.write(a >>> 8);
out.write(a);
byte[] gbk = "中国".getBytes("gbk");
out.write(gbk);
out.close();

IOUtil.printHex("demo/out.dat");

DataOutputStream

对”流”功能的拓展,可以更方便地写int,long,double,char等,常见用法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
String file = "demo/dos.dat";
DataOutputStream dos = new DataOutputStream(
new FileOutputStream(file));
dos.writeInt(10);
dos.writeInt(-10);
dos.writeLong(10l);
dos.writeDouble(10.5);
//采用utf-8编码写出
dos.writeUTF("中国");
//采用utf-16be编码写出
dos.writeChars("中国");
dos.close();
IOUtil.printHex(file);

DataInputStream

常见用法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
   String file = "demo/dos.dat";
IOUtil.printHex(file);
DataInputStream dis = new DataInputStream(
new FileInputStream(file));
int i = dis.readInt();
System.out.println(i);
i = dis.readInt();
System.out.println(i);
long l = dis.readLong();
System.out.println(l);
double d = dis.readDouble();
System.out.println(d);
String s = dis.readUTF();
System.out.println(s);

dis.close();

BufferedInputStream & BufferedOutputStream

这两个流类位IO提供了带缓冲区的操作,一般打开文件进行写入或读取操作时,都会加上缓冲,这种流模式提高了IO的性能.
从应用程序中把输入放入文件,相当于将一缸水倒入到另一个缸中:
FileOutputStream.write()方法相当于一滴一滴地把水“转移”过去.
DataOutputStream.writeXxx()方法会方便一些,相当于一瓢一瓢把水“转移”过去.
BufferedOutputStream.write()方法更方便,相当于一瓢一瓢先放入桶中,再从桶中倒入到另一个缸中,性能提高了.
利用带缓冲的字节流, 进行文件的拷贝:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static void copyFileByBuffer(File srcFile,File destFile)throws IOException{
if(!srcFile.exists()){
throw new IllegalArgumentException("文件:"+srcFile+"不存在");
}
if(!srcFile.isFile()){
throw new IllegalArgumentException(srcFile+"不是文件");
}
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(srcFile));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(destFile));
int c ;
while((c = bis.read())!=-1){
bos.write(c);
bos.flush();//刷新缓冲区
}
bis.close();
bos.close();
}

进程与线程

概念

  • 进程是==程序的执行过程==(动态性),持有资源(共享内存、共享文件)和线程(是资源和线程的载体)

  • 线程是系统中==最小的执行单元==

    线程间交互

  1. 互斥 资源有限,需抢占

  2. 同步 协作完成一项任务,有先后顺序

    java线程初探

    java对线程的支持

    Thread类和Runnable接口,以及共同的run()方法。
    java对线程的支持

    Thread类

    join()使当前运行线程等待调用线程的终止,再继续运行
    yield()使当前运行线程释放处理器资源
    停止线程的错误方法 1.stop() 2.interrupt()
    使用退出标志(volatile bool keepRunning)停止线程循环
    在这里插入图片描述

    Thread和Runnable示例

    Thread和Runnable各自每运行10次暂停1s,交替运行。一个.java文件可有多个类(不包括内部类),但只能有一个public类。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    public class Actor extends Thread {
    public void run(){
    System.out.println(getName()+"是一个演员!");
    int count = 0;
    boolean keepRunning = true;

    while(keepRunning){
    System.out.println(getName()+"登台演出:"+ (++count));
    if(count == 100){
    keepRunning = false;
    }
    if(count%10== 0){
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    System.out.println(getName()+"的演出结束了!");
    }
    public static void main(String[] args){
    Thread actor = new Actor();
    actor.setName("Mr. Thread");
    actor.start();
    Thread actressThread = new Thread(new Actress(),"Ms. Runnable");
    actressThread.start();
    }
    }
    class Actress implements Runnable{
    @Override
    public void run() {
    System.out.println(Thread.currentThread().getName()+"是一个演员!");
    int count = 0;
    boolean keepRunning = true;
    while(keepRunning){
    System.out.println(Thread.currentThread().getName()+"登台演出:"+ (++count));
    if(count == 100){
    keepRunning = false;
    }
    if(count%10== 0){
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    System.out.println(Thread.currentThread().getName()+"的演出结束了!");
    }
    }

    总结一下:
    在这里插入图片描述
    在这里插入图片描述

    线程的生命周期

    在这里插入图片描述
    阻塞事件:如sleep(),wait(),join()方法被调用

    java守护线程

    java线程分两类:
    1.用户线程
    2.守护线程 一旦所有用户线程都结束了,守护线程也就结束了
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    jstack生成线程快照

    在这里插入图片描述
    在这里插入图片描述

定义

对象序列化,就是将Object转换成byte序列,反之叫对象的反序列化.

  • 序列化流(ObjectOutputStream),是过滤流—-writeObject
  • 反序列化流(ObjectInputStream)—-readObject

序列化接口(Serializable)

对象必须实现序列化接口 ,才能进行序列化,否则将出现异常
这个接口,没有任何方法,只是一个标准.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
String file = "demo/obj.dat";
//1.对象的序列化
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(file));
Student stu = new Student("10001", "张三", 20);
oos.writeObject(stu);
oos.flush();
oos.close();
//2.对象的反序列化
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream(file));
Student stu = (Student)ois.readObject();
System.out.println(stu);
ois.close();

transient关键字

transient修饰的变量不会进行jvm默认的序列化,但可以自己完成这个元素的序列化.即覆写:

1
2
3
4
 private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class Student implements Serializable{
private String stuno;
private String stuname;
//该元素不会进行jvm默认的序列化,也可以自己完成这个元素的序列化
private transient int stuage;

public Student(String stuno, String stuname, int stuage) {
super();
this.stuno = stuno;
this.stuname = stuname;
this.stuage = stuage;
}

public String getStuno() {
return stuno;
}
public void setStuno(String stuno) {
this.stuno = stuno;
}
public String getStuname() {
return stuname;
}
public void setStuname(String stuname) {
this.stuname = stuname;
}
public int getStuage() {
return stuage;
}
public void setStuage(int stuage) {
this.stuage = stuage;
}
@Override
public String toString() {
return "Student [stuno=" + stuno + ", stuname=" + stuname + ", stuage="
+ stuage + "]";
}
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
s.defaultWriteObject();//把jvm能默认序列化的元素进行序列化操作
s.writeInt(stuage);//自己完成stuage的序列化
}
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException{
s.defaultReadObject();//把jvm能默认反序列化的元素进行反序列化操作
this.stuage = s.readInt();//自己完成stuage的反序列化操作
}
}

ArrayList源码中对elementData数组序列化和反序列化的处理,因为elementData数组中不是所有元素都是有效元素,所以只序列化了size个有效元素.
在这里插入图片描述
在这里插入图片描述

序列化中 子父类构造函数的调用问题

一个类实现了序列化接口,那么其子类都可以进行序列化.
子类对象进行反序列化操作时,如果其父类没有实现序列化接口,那么其父类的构造函数会被调用.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
public class ObjectSeriaDemo2 {
public static void main(String[] args) throws Exception{
//序列化Foo2
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("demo/obj1.dat"));
Foo2 foo2 = new Foo2();
oos.writeObject(foo2);
oos.flush();
oos.close();

//反序列化Foo2是否递归调用父类的构造函数?不会调用Foo1(),Foo()
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("demo/obj1.dat"));
Foo2 foo2 = (Foo2)ois.readObject();
System.out.println(foo2);
ois.close();

//序列化Bar2
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("demo/obj1.dat"));
Bar2 bar2 = new Bar2();
oos.writeObject(bar2);
oos.flush();
oos.close();

//反序列化Bar2是否递归调用父类的构造函数?会调用Bar1(),Bar()
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("demo/obj1.dat"));
Bar2 bar2 = (Bar2)ois.readObject();
System.out.println(bar2);
ois.close();


/*
* 对子类对象进行反序列化操作时,
* 如果其父类没有实现序列化接口
* 那么其父类的构造函数会被调用
*/
}
}
/*
* 一个类实现了序列化接口,那么其子类都可以进行序列化
*/
class Foo implements Serializable{
public Foo(){
System.out.println("foo...");
}
}
class Foo1 extends Foo{
public Foo1(){
System.out.println("foo1...");
}
}
class Foo2 extends Foo1{
public Foo2(){
System.out.println("foo2...");
}
}
class Bar{
public Bar(){
System.out.println("bar");
}
}
class Bar1 extends Bar{
public Bar1(){
System.out.println("bar1..");
}
}
class Bar2 extends Bar1 implements Serializable{
public Bar2(){
System.out.println("bar2...");
}
}

关机与重启

shutdown命令

安全的关机命令shutdown [选项] 时间
关机时会自动保存运行数据
时间为now则立即执行,或23:30定时关机

选项 说明
-c 取消前一个关机命令
-h 关机
-r 重启

不安全的关机:halt, poweroff, init 0等,尽量不用
重启:reboot可用,较安全,init 6尽量不用

系统运行级别

runlevel可查看系统运行级别

系统运行级别 说明
0 关机
1 单用户(类似win安全模式)
2 不完全多用户,不含NFS(文件共享)服务
3 完全多用户 常用
4 未分配
5 图形界面
6 重启

CentOS系统启动的默认运行级别initdefault的设置在/etc/inittab中,initdefault不能改为0或6,否则无法开机!

退出登录

logout
linux默认最多允许256个用户同时登录
winXP默认最多允许1个用户同时登录
winSever 2003默认最多允许2个用户同时登录
winSever 2008默认最多允许4-8个用户同时登录
直接关闭终端窗口并不能退出用户,终端号没有释放,一定要手动logout

用户登录

1
2
[root@主机名 ~] # root(超级)用户
[xxxx@主机名 ~] $ 普通用户

切换默认shell

1
2
chsh -s /usr/bin/fish
grep root /etc/passwd

快速删除,移动光标

键盘快捷键:

1
2
3
4
5
6
ctrl + w 往回删除一个单词,光标放在最末尾
ctrl + u 删除光标以前的字符
ctrl + k 删除光标以后的字符
ctrl + a 移动光标至的字符头
ctrl + e 移动光标至的字符尾
ctrl + l 清屏

已知进程pid获取其父进程pid

1
2
ps -ef  #查看所有用户进程
ps -ef|awk '$2 ~ /pid/{print $3}

tar打包解包

1
2
tar -zcvf xx.tar.gz xx  
tar -zxvf xx.tar.gz xx

tail命令

用于查看纯文本文档的后N行或持续刷新内容

1
tail [选项] [文件]

判断字符串长度

1
2
3
4
ID=12345
if [ ${#ID} -eq 5 ];then
echo "5"
fi

将命令的输出结果赋值给变量

1
2
3
4
5
6
#!/bin/bash
begin_time=`date` #开始时间,使用``替换
sleep 20s #休眠20秒
finish_time=$(date) #结束时间,使用$()替换
echo "Begin time: $begin_time"
echo "Finish time: $finish_time"

文件类型

1
2
3
4
ls  -lh  # --long   --human人性化显示大小
ll # ls -l
drwx------ 2 root root 4096 Nov 3 10:13 Downloads
引用计数

linux中有6中文件类型,常用的三种为:
-普通文件 d目录 l软连接
在这里插入图片描述
在这里插入图片描述