JAVA基础

一些JAVA基础知识

1、数组

1.1 创建与初始化

1
2
int[] a = new int[] {1,3,8,1,55,6};
int b[] = new int[2];

1.2 复制数组

1
System.arraycopy(a, 0, b, 1, 1); // 从a数组的0下标复制1个到b数组的1下标

1.3 二维数组

1
2
3
4
5
6
7
class ErWeiShuZu {
void method() {
int [][] x = new int[5][];
x[0] = new int[2];
System.out.println(x[0][1]); // 0
}
}

1.4 数组作为方法参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class ArrayUse {
void method(int a[]) {
a[0] = 5;
// 转换为string
System.out.println(Arrays.toString(a));
// 复制一定区域
System.out.println(Arrays.toString(Arrays.copyOfRange(a, 0, 3)));
// 排序
Arrays.sort(a);
System.out.println(Arrays.toString(a));
// 搜索(先进行sort)
System.out.println(Arrays.binarySearch(a, 8));
// 相同
int []b = Arrays.copyOfRange(a, 0, 6);
System.out.println(Arrays.equals(a, b)); // true
b[2] = 555;
System.out.println(Arrays.equals(a, b)); // false
}
}

主函数调用:

1
2
3
int[] a2 = new int[] {1,3,8,1,55,6};
new ArrayUse().method(a2);
new ShuZu().outputArr(a2); // 输出,a2作为方法参数,已被改变

1.5 排序

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
import java.util.Scanner;

public class SortFun {
int arr[];
int arrsize = 0;
void inputArr() {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt(); // 数量
arr = new int[num];
arrsize = num;
for (int i = 0; i < num; i++) {
arr[i] = sc.nextInt();
}
}
void selectSort() { // 选择排序
for (int i = 0; i < arrsize; i++) {
// 比较后续是否有比arr[i]小的
// 有则交换
for (int j = i + 1; j < arrsize; j++) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}

void bubbleSort() {
for (int i = 0; i < arrsize - 1; i++) { // arrsize - 1次冒泡泡
for (int j = 0; j < arrsize - i - 1; j++) { // arrsize - i - 1次交换
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void outputArr() {
for (int arri : arr) { // 增强型for循环
System.out.print(arri);
System.out.print(" ");
}
System.out.println();
}
public static void main(String[] args) {
SortFun sf = new SortFun();
sf.inputArr();
// sf.selectSort();
sf.bubbleSort();
sf.outputArr();
}
}

2、类与对象

2.1 命名规范

  1. 类的第一个字母大写;
  2. 方法addSpeed().
  3. 属性一般小写.

    2.2 引用

    引用与指向

    new一个对象仅仅代表新建一个对象,没有办法访问它;而使用=给引用赋对象值,代表该对象,又叫“指向”;
    1
    2
    //使用一个引用来指向这个对象
    Lei h1 = new Lei();

    多个引用,一个对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    //使用一个引用来指向这个对象
    Lei h1 = new Lei();
    System.out.println(h1.name);
    h1.name = "Cct";
    Lei h2 = h1; //h2指向h1所指向的对象
    Lei h3 = h1;
    Lei h4 = h1;
    Lei h5 = h4;
    System.out.println(h5.name);
    h4.name = "abc";
    System.out.println(h1.name);
    //h1,h2,h3,h4,h5 五个引用,都指向同一个对象

    一个引用,多个对象

    当某个对象没有任何引用指向,就会被垃圾回收。

2.3 this的指向

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
class Hero {

String name; //姓名

float hp; //血量

float armor; //护甲

int moveSpeed; //移动速度

//参数名和属性名一样
//在方法体中,只能访问到参数name
public void setName1(String name){
System.out.printf("方法参数与属性名称相同时:%s\n",name);
name = name;
}

//为了避免setName1中的问题,参数名不得不使用其他变量名
public void setName2(String heroName){
name = heroName;
}

//通过this访问属性
public void setName3(String name){
//name代表的是参数name
//this.name代表的是属性name
this.name = name;
}

void method() {
Hero h =new Hero();
Hero h2 =new Hero();
h.setName1("teemo");
System.out.println(h.name); // null

h.setName2("garen");
System.out.println(h.name); // garen

System.out.println(h2.name);
h2.setName3("死歌");
System.out.println(h2.name);
// 死歌
}

}

2.4 函数对象参数改变不影响实参

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

class Hero2 {

String name; //姓名

float hp; //血量

float armor; //护甲

int moveSpeed; //移动速度

public Hero2(){

}

public Hero2(String name,float hp){
this.name = name;
this.hp = hp;
}

//复活
public void revive(Hero2 h){
h = new Hero2("提莫",383); // 指向新的引用
}

void method() {
Hero2 teemo = new Hero2("提莫",383);

//受到400伤害,挂了
teemo.hp = teemo.hp - 400;

teemo.revive(teemo);

//问题: System.out.println(teemo.hp); 输出多少? 怎么理解
// -17
System.out.println(teemo.hp);
}

}

2.5 对象属性初始化顺序

声明函数初始化 -> 初始化块 -> 构造函数初始化

1
2
3
4
5
6
7
8
9
10
11
12
class Hero3 {
public String name = "hero1"; // 声明函数初始化
public Hero3() { // 构造函数初始化(最终结果)
name = "hero2";
}
{
name = "hero3"; // 初始化块
}
void method() {
System.out.println(name); // hero2
}
}

2.6 枚举类

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
class EnumLei {
public enum HeroType {
TANK, WIZARD, ASSASSIN, ASSIST, WARRIOR, RANGED, PUSH, FRAMING
}
public void method() {
for (HeroType h: HeroType.values()) {
System.out.println(h);
}
HeroType h = HeroType.RANGED;
switch(h) {
case TANK:
System.out.println("坦克");
break;
case WIZARD:
System.out.println("法师");
break;
case ASSASSIN:
System.out.println("辅助");
break;
default:
System.out.println("okkkk");
break;
}
}
}

2.7 单例模式

饿汉式单例模式

立即加载

  1. 将构造函数私有化,使在外部不能通过new新建一个对象,只能使用公有的getInstance方法;
  2. 一个实例化对象作为类属性(static);
  3. 每次获取都得到同一个实例对象,即该类属性。

    懒汉式单例模式

延时加载
与上面不同的是,类属性先不指向一个对象,而是在getInstance()中判断该引用是否为null,若是再new一个,否则直接返回。

3、接口与继承

接口

1
2
3
4
5
6
7
package animalUML;

public interface Pet {
String getName();
void setName(String name);
void play();
}

抽象类

1
2
3
4
5
6
7
8
9
10
11
12
package animalUML;

public abstract class Animal {
protected int legs;
public Animal(int a) {
legs = a;
}
abstract void eat();
public void walk() {
System.out.println("用"+legs+"只脚走路");
}
}

继承

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
package animalUML;
public class AllAnimals {
public static void main(String[] args) {
Animal spider = new Spider();
spider.eat(); // 调用在子类中定义的抽象方法
spider.walk(); // 抽象类自带方法

Cat cat = new Cat("mimi");
cat.eat();
cat.walk(); // 抽象类方法
cat.setName("lucy");
cat.play(); // 接口方法

Fish fish = new Fish("yuyu");
fish.walk(); // 子类定义的抽象方法覆盖了父类

// System.out.println(cat.name); 不可访问的私有属性
System.out.println(fish.name);

// Animal a = new Animal(0); animal是抽象类 不可直接实例化
}
}

class Spider extends Animal {
Spider() {
super(8);
}
@Override
void eat() {
// TODO Auto-generated method stub
System.out.println("蜘蛛吃人!!");
}
}

class Cat extends Animal implements Pet {
private String name;
Cat(String name) {
super(4);
this.name = name;
}
Cat() {
super(4);
this.name = " ";
}
// 接口方法
@Override
public String getName() {
// TODO Auto-generated method stub
return this.name;
}
@Override
public void setName(String name) {
// TODO Auto-generated method stub
this.name = name;
}
@Override
public void play() {
// TODO Auto-generated method stub
System.out.println("小猫咪"+this.name+"在玩!");
}
// 抽象方法
@Override
void eat() {
// TODO Auto-generated method stub
System.out.println("小猫咪"+this.name+"在吃!");
}
}

class Fish extends Animal implements Pet {
String name;
Fish(String name) {
super(0);
this.name = name;
}
Fish () {
super(0);
}
@Override
public String getName() {
// TODO Auto-generated method stub
return this.name;
}
@Override
public void setName(String name) {
// TODO Auto-generated method stub
this.name = name;
}
@Override
public void play() {
// TODO Auto-generated method stub
System.out.println("小鱼"+this.name+"在玩!");
}
@Override
void eat() {
// TODO Auto-generated method stub
System.out.println("小鱼"+this.name+"在吃!");
}
public void walk() {
System.out.println("小鱼"+this.name+"游啊游");
}
}

4、多态

接口

1
2
3
4
5
package DuoTai;
// 接口只能包含方法名
public interface MortalInterface {
public void die();
}

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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/*
* 英雄类
*/
package DuoTai;

public class Hero implements Comparable<Hero>{
static String copyright;
static {
System.out.println("初始化copyright");
copyright = "cct";
}
synchronized static public void test () {
for (int i =0; i < 20; i++) {
System.out.print(i + " ");
}
System.out.println();
}
String name;
public int hp;
String type;
public int damage;
// 构造方法
public Hero () {

}
public Hero (String name, int hp, String type) {
this.name = name;
this.hp = hp;
this.type = type;
}
public Hero (String name, int hp, int damage) {
this.name = name;
this.hp = hp;
this.damage = damage;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
void kill(MortalInterface m) {
m.die();
}
static void battlewin( ) {
System.out.println("hero wins!!!");
}
public String toString() {
return "Hero:[name: " + this.name + ", hp: " + this.hp + ", damage: " + this.damage + "]" ;
}
// 重写比较函数
// 按伤害从高到低
@Override
public int compareTo(Hero o) {
// TODO Auto-generated method stub
if (damage < o.damage) return 1; // > 0 伤害小的排后面去 新来的的排前面去
return -1;
}
// 判断血量是否为0
public boolean isDead() {
return hp <= 0 ? true:false;
}
// 攻击另一个英雄
public void attackHero(Hero h) {
/*try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// 中断异常
// sleep过程中被停止
e.printStackTrace();
}
/*if (this.isDead()) {
System.out.println(name + "挂了!");
return;
}*/
h.hp -= damage;
System.out.format("%s正在攻击%s,%s的血量变成%d%n", name, h.name, h.name, h.hp);
if (h.isDead()) {
System.out.println(h.name + "挂了!");
}
}

// 掉血
synchronized public void hurt() {
hp -= 1;
System.out.println("当前血量" +hp);
}
// 回血
synchronized public void recover() {
hp += 1;
System.out.println("当前血量" +hp);
}
}

class ADHero extends Hero implements MortalInterface{
ADHero(String name, int hp) {
super(name, hp, "ADHero");
// 若没有上面的super,则默认调用父类的无参构造函数
// TODO Auto-generated constructor stub
}
ADHero(){
super("nothing", 0, "ADHero");
}

@Override
public void die() {
// TODO Auto-generated method stub
System.out.println(this.type + " die!ad die hh");
}
// 重写类方法
static void battlewin() {
System.out.println("adhero wins!!!");
}
}

class APHero extends Hero implements MortalInterface{
APHero(String name, int hp) {
super(name, hp, "APHero");
// TODO Auto-generated constructor stub
}

@Override
public void die() {
// TODO Auto-generated method stub
System.out.println(this.type + " die!ap die hh");
}
}

class ADAPHero extends Hero implements MortalInterface{
ADAPHero(String name, int hp) {
super(name, hp, "ADAPHero");
// TODO Auto-generated constructor stub
}

@Override
public void die() {
// TODO Auto-generated method stub
System.out.println(this.type + " die!adap die hh");
}
}

主函数

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
package DuoTai;

public class DuoTai {

public static void main(String[] args) {
// TODO Auto-generated method stub
Hero h = new Hero("cct", 1000, "hero");
ADHero ad = new ADHero("ad", 100);
APHero ap = new APHero("ap", 100);
ADAPHero adap = new ADAPHero("adap", 100);
h.kill(ad); // kill是hero统一方法,kill方法中根据不同对象调用实现的不同的接口方法die()
h.kill(ap);
h.kill(adap);
Hero.battlewin();

Hero h2 = new ADHero("ad2", 100);
h2.battlewin(); // 结果是hero类的静态方法

// Object方法
Hero h11 = new Hero("cct",1000,"hero");
Hero h22 = new Hero("cct",1000,"hero");
Hero h33 = new Hero("cct",1000,"hero");
h33 = h11;
System.out.println(h11 == h22); // false
System.out.println(h11.equals(h22)); // false
System.out.println(h11.equals(h33)); // true

System.out.println(h11.toString());
System.out.print(h11.getClass());
}

}

5、文件输入输出流

5.1 一些文件函数

1
2
3
4
File f = new File("src");
System.out.println(f.getAbsolutePath());
System.out.println(f.exists());
File[] fs = f.listFiles();

5.2 获取文件列表

1
2
3
4
5
6
7
8
9
10
11
  void getFiles(File[] fs) {
for (File f:fs) {
if (f.isDirectory()) {
File[] next_fs = f.listFiles();
getFiles(next_fs);
}
else {
System.out.println(f.toString());
}
}
}

5.2 字节流读取文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
   void readFile(File f) {
try {
FileInputStream fis = new FileInputStream(f);
byte[] all = new byte[(int) f.length()];
fis.read(all);// 字节流形式读出
for (byte b:all) {
System.out.print((char)b);
}
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

5.3 字节流写入文件

1
2
3
4
5
6
7
8
9
10
11
12
   void writeFile(File f) {
try {
FileOutputStream fos = new FileOutputStream(f);
byte data[] = {96,97};
fos.write(data);
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

5.4 字符流读取文件

1
2
3
4
5
6
7
8
9
10
11
12
13
   void readFile2(File f) {
try {
FileReader fr = new FileReader(f);
char[] all = new char[(int)f.length()];
fr.read(all);
for (char b: all) {
System.out.print(b);
}
fr.close();
} catch(IOException e) {
e.printStackTrace();
}
}

5.5 字符流写入文件

1
2
3
4
5
6
7
8
9
10
11
12
13
void writeFile2(File f) {
try {
FileWriter fw = new FileWriter(f);
String data = "我是陈彩婷!";
char[] cs = data.toCharArray();
fw.write(cs);
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

6、集合框架

6.1 arraylist

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
package arrayListLearn;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import DuoTai.Hero;

public class ArrayListLearn {
public void outputArray(List<Hero> heros) {
// 增强型for循环
/*for (Object hero : heros) {
System.out.println(hero.toString());
}*/
// 迭代器while循环
Iterator<Hero> it = heros.iterator();
while (it.hasNext()) {
Hero hero = it.next();
System.out.println(hero.toString());
}
System.out.println("******************************");
}

@SuppressWarnings("rawtypes")
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Hero> heros = new ArrayList<Hero>();
heros.add(new Hero("cct", 1000, "hero"));
heros.add(new Hero());
// 在特定的位置上添加
Hero spHero = new Hero("sphero", 100, "hero");
heros.add(1, spHero);
// 数组大小
System.out.println(heros.size());
// 遍历
// 调用重写的toString方法
new ArrayListLearn().outputArray(heros);
// 获取指定位置的对象
System.out.println(heros.get(0));
// 判断对象是否存在
System.out.println(heros.contains(spHero));
// 获取对象所处的位置
System.out.println(heros.indexOf(spHero));
System.out.println(heros.lastIndexOf(spHero));
// 按下标删除对象
heros.remove(heros.size() - 1);
new ArrayListLearn().outputArray(heros);
// 按下标替换对象
Hero spHero2 = new Hero("sphero2", 100, "hero");
heros.set(1, spHero2);
// heros.set(2, spHero2); 越界
new ArrayListLearn().outputArray(heros);
// 按对象删除
heros.remove(spHero2);
new ArrayListLearn().outputArray(heros);
// 转换为数组
Hero hs[] = (Hero[])heros.toArray(new Hero[] {});
System.out.println(hs);
// 初始化5个对象
ArrayList<Hero> anotherHeros = new ArrayList<Hero>();
for (int i = 0; i < 5; i++) {
anotherHeros.add(new Hero("hero " + i, 10,"hero"));
}
// 容器相加
heros.addAll(anotherHeros);
new ArrayListLearn().outputArray(heros);
// 容器清空
anotherHeros.clear();
new ArrayListLearn().outputArray(anotherHeros);
}
}

6.2 linkedlist

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
package linkListLearn;

import java.util.LinkedList;
import java.util.Queue;

import DuoTai.Hero;
import arrayListLearn.ArrayListLearn;

public class LinkedListLearn {
public static void main(String[] args) {
// 双向链表
// 实现了List Deque
LinkedList<Hero> l1 = new LinkedList<Hero>();
// 在后面插入新的英雄
for (int i = 0; i < 5; i++) {
l1.addLast(new Hero("hero " + i, 10, "hero"));
}
// 在前面插入新的英雄
l1.addFirst(new Hero("hero 00", 10, "hero"));
// 调用别包的方法 需要是public
// 默认是package,只有包内可用
ArrayListLearn al = new ArrayListLearn();
al.outputArray(l1);
// 查看与删除
// getFirst() removeFirst()

// 实现Queue接口
Queue<Hero> q1 = l1; // 大的包容小的
// 从队尾入
q1.offer(new Hero("hero tail", 10, "hero"));
// 查看队头
System.out.println(q1.peek());
// 从队头出
Hero h = q1.poll();
System.out.println(h);
LinkedList<Hero> l2 = new LinkedList<Hero>();
l2 = (LinkedList<Hero>)q1; // 从大到小 强制转换
al.outputArray(l2);
}
}

6.3 hashset

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
package hashLearn;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Random;

import DuoTai.Hero;

public class HashSetLearn {

void queryList() {
List<Integer> myList = new ArrayList<>();
for (int i = 0; i < 2000000; i++) {
myList.add(i + 1);
}
// 进行10次查找
for (int i = 0; i < 10; i++) {
// 打乱数组
Collections.shuffle(myList);
// 获取当前时间
long start = System.currentTimeMillis();
for (Integer num : myList) {
if (num == 100000) {
System.out.println("find 100000!");
break;
}
}
// 获取结束时间
long end = System.currentTimeMillis();
System.out.printf("花了%d毫秒\n",end-start);
}

System.out.println("-----------------------");
}

void queryHashMap() {
HashMap<Integer, Integer> myMap = new HashMap<>();
for (int i = 0; i < 2000000; i++) {
myMap.put(i + 1, i + 1);
}
for (int i = 0; i < 10; i++) {
// 获取当前时间
long start = System.currentTimeMillis();
int target = myMap.get(100000);
System.out.println("find "+ target);
long end = System.currentTimeMillis();
System.out.printf("花了%d毫秒\n",end-start);
}
System.out.println("-----------------------");
}

public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<String> hs = new HashSet<>();
// 生成随机数
Random random = new Random();
for (int i = 0; i < 5; i++) {
hs.add("aa"+random.nextInt(6));
}
// 发生插入则返回true
// 反之返回false
System.out.println(hs.add("aa5"));
System.out.println(hs);
System.out.println(hs.size());

HashSetLearn hsl = new HashSetLearn();
// hsl.queryList();
// hsl.queryHashMap();

// 存储类型的hashset
HashSet<Hero> hs2 = new HashSet<>();
for (int i = 0; i < 5; i++) {
hs2.add(new Hero("hero " + i, 10, "hero"));
}
// 发生插入则返回true
// 反之返回false
Hero ahero = new Hero("hero 0", 10, "hero");
System.out.println(hs2.add(ahero)); // true
// equals判断为true 所以不能进行进一步添加
System.out.println(hs2.add(ahero)); // false
System.out.println(hs2);
System.out.println(hs2.size());
}

}

7、匿名类

接口方法

1
2
3
4
5
6
7
package lambdaLearn;

import DuoTai.Hero;

public interface HeroChecker {
public boolean test(Hero h);
}

主函数

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
package lambdaLearn;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import DuoTai.Hero;
import arrayListLearn.ArrayListLearn;

public class LambdaLearn {

public static void main(String[] args) {
// TODO Auto-generated method stub
Hero h_cct = new Hero("cct",1000,50);
List<Hero> hero_list = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < 10; i++) {
hero_list.add(new Hero("hero" + (i + 1), random.nextInt(1000), random.nextInt(50)));
}
hero_list.add(h_cct);
ArrayListLearn al = new ArrayListLearn();
al.outputArray(hero_list);

// 排序
System.out.println("排序后:");
Collections.sort(hero_list);
al.outputArray(hero_list);
// 1. 显示实现test接口方法
// 筛选 传入匿名类对象
System.out.println("筛选damage>=30的后:");
HeroChecker checker = new HeroChecker() {
public boolean test(Hero h) {
return (h.damage < 30);
}
};
// filter方法只有是static,才能直接调用
List<Hero> new_hero_list1 = filter(hero_list, checker);
al.outputArray(new_hero_list1);

// 2.1 匿名类:精简接口方法
// 筛选 传入Lambda
// Lambda类实际上就是一个参数->判断bool函数
System.out.println("筛选hp>=800的后:");
List<Hero> new_hero_list2 = filter(hero_list, (h)->h.hp < 800);
al.outputArray(new_hero_list2);

// 2.2
// Lambda排序方式
// sort是一个筛选函数 当实现的接口方法返回1时 发生位置调换 即小的h1换到大的h2后面 所以是从大到小
System.out.println("对hp进行从大到小的排序后:");
Collections.sort(new_hero_list2, (h1, h2)->h1.hp < h2.hp ? 1:-1); // 1:后面的排在前面 ;-1:后面的还是在后面
al.outputArray(new_hero_list2);

// 3.
// Lambda调用静态方法
// List<Hero> new_hero_list3 = filter(hero_list, h->testHero(h));
List<Hero> new_hero_list3 = filter(hero_list, LambdaLearn::testHero);
al.outputArray(new_hero_list3);
// 还可以引用对象方法,容器中对象的方法

// 聚合操作
System.out.println("聚合操作:");
Hero thirdhero = hero_list
.stream() // Collection切换为管道源
.sorted((h1, h2) -> h1.hp < h2.hp?1:-1) // 中间操作:按照hp从高到低排序
.skip(2) // 中间操作:跳过前2个
.findFirst() // 结束
.get();
System.out.println(thirdhero);
}
private static List<Hero> filter(List<Hero> heros, HeroChecker hc) {
List<Hero> new_heros = new ArrayList<>();
for (Hero h : heros) {
if (!hc.test(h)) { // 筛选器 当返回true时 选上
new_heros.add(h);
}
}
return new_heros;
}
private static boolean testHero(Hero h) {
return h.hp < 800 && h.damage < 30;
}

}

8、多线程

8.1 线程的一些基本操作

实现线程的3种方式:

  1. 继承Thread
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    package multipleThread;

    import DuoTai.Hero;

    public class KillThread extends Thread{
    private Hero h1;
    private Hero h2;

    public KillThread(Hero h1, Hero h2) {
    this.h1 = h1;
    this.h2 = h2;
    }

    public void run() {
    while (!h2.isDead()) {
    h1.attackHero(h2);
    }
    }
    }
  2. Battle类实现runnable接口:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    package multipleThread;

    import DuoTai.Hero;

    public class Battle implements Runnable{
    Hero h1;
    Hero h2;
    Battle(Hero h1, Hero h2) {
    this.h1 = h1;
    this.h2 = h2;
    }
    @Override
    public void run() {
    // TODO Auto-generated method stub
    while (!h2.isDead()) {
    h1.attackHero(h2);
    }
    }

    }
  3. 匿名类
    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
    /*
    * 多线程例子
    */
    package multipleThread;

    import DuoTai.Hero;

    public class MultipleThread {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Hero h1 = new Hero("A", 2500, 5);
    Hero h2 = new Hero("B", 2000, 8);
    /*
    * 顺序
    while (!h2.isDead()) {
    h1.attackHero(h2);
    }

    while (!h1.isDead()) {
    h2.attackHero(h1);
    }
    */
    // 多线程
    // 继承Thread
    /*
    KillThread kt1 = new KillThread(h1, h2);
    kt1.start(); // 借助一个线程对象的start方法,才会启动一个线程
    KillThread kt2 = new KillThread(h2, h1);
    kt2.start();
    */
    //或实现Runnable接口
    /*
    Battle b1 = new Battle(h1, h2);
    Battle b2 = new Battle(h2, h1);
    new Thread(b2).start();
    new Thread(b1).start();
    */
    // 或匿名类
    // A攻击B
    Thread t1 = new Thread() {
    public void run() {
    // 可直接使用外部final变量
    // JDK7之后无要求
    while (!h2.isDead()) {
    h1.attackHero(h2);
    }
    }
    };
    // B攻击A
    Thread t2 = new Thread() {
    public void run() {
    while (!h1.isDead()) {
    Thread.yield(); // 临时暂停
    h2.attackHero(h1);
    }
    }
    };
    t1.setPriority(1);
    t2.setPriority(10); // 优先级大的抢占CPU能力强
    t1.start();
    t2.start();
    /*
    try {
    t1.join(); // 加入到主线程中
    t2.join();
    } catch(InterruptedException e) {
    e.printStackTrace();
    }
    */
    System.out.println("Game Over!!!");
    }

    }

    8.2 原子操作

    普通int不能做到并发操作,而AtomicInteger可以
    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
    package multipleThread;

    import java.util.concurrent.atomic.AtomicInteger;

    public class AtomicTest {

    private static int value = 0;
    private static AtomicInteger aint = new AtomicInteger();
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    int number = 100000;
    Thread[] t1 = new Thread[number];
    for (int i = 0; i < number; i++) {
    Thread t = new Thread() {
    public void run() {
    value++;
    }
    };
    t.start();
    t1[i] = t;
    }

    for (Thread t: t1) {
    try {
    t.join();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    System.out.println("value:" + value);
    Thread t2[] = new Thread[number];
    for (int i = 0; i < number; i++) {
    Thread t = new Thread() {
    public void run() {
    aint.incrementAndGet(); // 原子操作:自增
    }
    };
    t.start();
    t2[i] = t;
    }

    for (Thread t:t2) {
    try {
    t.join();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    System.out.println("aint:" + aint.intValue());
    }

    }

    8.3 synchronized

    Hero类的recover方法与hurt方法有synchronized关键词修饰:
    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
    /**
    * 进程同步
    */
    package multipleThread;

    import DuoTai.Hero;

    public class KeyTest {

    public static void main(String[] args) throws InterruptedException {
    // TODO Auto-generated method stub
    final Hero h = new Hero("cct", 1000, 50);
    System.out.printf("初始血量为%d\n", h.hp);

    // n个线程
    int n = 10000;
    Thread[] addThreads = new Thread[n];
    Thread[] reduceThreads = new Thread[n];

    // 匿名类建立n个线程增加hp
    for (int i = 0; i < n; i++) {
    Thread t = new Thread() {
    public void run() {
    h.recover();
    try {
    Thread.sleep(100);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    };
    t.start();
    addThreads[i] = t;
    }
    // 匿名类建立n个线程减少hp
    for (int i = 0; i < n; i++) {
    Thread t = new Thread() {
    public void run() {
    h.hurt();
    try {
    Thread.sleep(100);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    };
    t.start();
    reduceThreads[i] = t;
    }
    // 等待所有增加线程结束
    for (Thread t : addThreads) {
    try {
    t.join();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    // 等待所有减少线程结束
    for (Thread t : reduceThreads) {
    t.join();
    }
    System.out.print(h.hp); // 初始血量1000
    }

    }

    8.4 await signal signalAll

    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
    package multipleThread;

    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;

    public class LockTest {
    // 获取当前时间
    public static String now() {
    return new SimpleDateFormat("HH:mm:ss").format(new Date());
    }
    // 打印日志
    public static void log(String msg) {
    System.out.printf("%s %s %s%n", now(), Thread.currentThread().getName(), msg);
    }

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();// await signal signalAll方法

    Thread t1 = new Thread() {
    public void run() {
    boolean locked = false;
    try {
    log("线程启动");
    log("试图lock");
    lock.lock();
    log("已占有(5s)");
    Thread.sleep(5000);
    log("临时释放lock对象,并等待");
    condition.await(); // 自身陷入等待
    log("重新占有lock,继续5s");
    Thread.sleep(5000);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } finally {
    log("释放对象unlock");
    lock.unlock();
    }
    log("线程结束");
    }
    };
    t1.setName("t1");
    t1.start();
    try {
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    Thread t2 = new Thread() {
    public void run() {
    boolean locked = true;
    try {
    log("线程启动");
    log("试图lock");
    // lock.lock();
    locked = lock.tryLock(6, TimeUnit.SECONDS); // 试图占有操作,时限1s
    if (locked) {
    log("已占有(5s)");
    Thread.sleep(5000);
    log("唤醒");
    condition.signal();
    } else {
    log("1s内没能成功占有 Sorry");
    }
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } finally {
    if (locked) { // 在占有对象的前提下
    log("释放对象unlock");
    // lock.unlock();
    }
    }
    log("线程结束");
    }
    };
    t2.setName("t2");
    t2.start();
    }

    }

    8.5 死锁实例

    hero实例对象使用synchronized修饰
    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
    package multipleThread;

    import DuoTai.Hero;

    public class LockDemo {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    final Hero h1 = new Hero("hero1", 1000, 10);
    final Hero h2 = new Hero("hero2", 1000, 10);
    final Hero h3 = new Hero("hero3", 1000, 10);

    Thread t1 = new Thread() {
    public void run() {
    synchronized (h1) {
    System.out.println("t1占有h1!");
    try {
    Thread.sleep(100);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    System.out.println("t1想去占有h2");
    synchronized (h2) {
    System.out.println("nothing");
    }
    }
    }
    };
    t1.start();
    Thread t2 = new Thread() {
    public void run() {
    synchronized (h2) {
    System.out.println("t2占有h2!");
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    System.out.println("t2想去占有h3");
    synchronized (h3) {
    System.out.println("nothing");
    }
    }
    }
    };
    t2.start();
    Thread t3 = new Thread() {
    public void run() {
    synchronized (h3) {
    System.out.println("t3占有h3!");
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    System.out.println("t3想去占有h1");
    synchronized (h1) {
    System.out.println("nothing");
    }
    }
    }
    };
    t3.start();
    }

    }

    8.6 生产者与消费者

    两种方式

    synchronized与信号量方式

    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
    /*
    * 生产者-消费者
    */
    package multipleThread;

    import java.util.Random;
    import java.util.Stack;

    class MyStack<E> {
    private Stack<E> ms = new Stack<E>();
    private int limit = 10; // 栈的大小
    public MyStack(int l) {
    this.limit = l;
    }
    // 在栈满的情况下 使当前进程wait
    // 将item压入栈
    // 通知消费者wait进程可拿
    synchronized void push(E item) throws InterruptedException {
    while (ms.size() == limit) this.wait(); // 使用while再次确认 防止虚假唤醒
    ms.push(item);
    System.out.println("当前stack大小为"+ms.size());
    notifyAll();
    }
    // 在栈空的情况下 使当前进程wait
    // 将item取出栈
    // 通知生产者wait进程可放
    synchronized E pop() throws InterruptedException {
    while (ms.size() == 0) this.wait();
    E item = ms.pop();
    System.out.println("当前stack大小为"+ms.size());
    notifyAll();
    return item;
    }
    }

    public class PCproblem {
    public static void main(String[] args) {
    MyStack<Integer> ms = new MyStack(10); // 临界区
    // TODO Auto-generated method stub
    Thread producer = new Thread() {
    public void run() {
    Random r = new Random();
    try {
    while (true) {
    int x = r.nextInt(10);
    ms.push(x);
    System.out.println("压入"+ x);
    Thread.sleep(1000);
    }
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    };
    producer.start();

    Thread[] consumer = new Thread[3];
    for (int i = 0; i < 3; i++) {
    Thread t = new Thread() {
    public void run() {
    try {
    while (true) {
    int x = ms.pop();
    System.out.println("弹出"+ x);
    Thread.sleep(1000);
    }
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    };
    consumer[i] = t;
    t.start();
    }
    }

    }

    lock法

    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
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    /*
    * 生产者-消费者
    */
    package multipleThread;

    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Random;
    import java.util.Stack;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;

    class MyNewStack<E> {
    private Stack<E> ms = new Stack<E>();
    private int limit = 10; // 栈的大小
    Lock lock = new ReentrantLock(); // 创建锁对象
    Condition condition = lock.newCondition();

    // 获取当前时间
    public static String now() {
    return new SimpleDateFormat("HH:mm:ss").format(new Date());
    }
    // 打印日志
    public static void log(String msg) {
    System.out.printf("%s %s %s%n", now(), Thread.currentThread().getName(), msg);
    }

    public MyNewStack(int l) {
    this.limit = l;
    }
    // 在栈满的情况下 使当前进程wait 释放锁
    // 不能使用synchronized关键字,因为使用后确保对stack的互斥访问 尽管await了,还是上着锁
    // 当栈不满后,将item压入栈
    // 通知消费者wait进程可拿
    void push(E item) throws InterruptedException {
    try {
    lock.lock();
    while (ms.size() == limit) {
    log("栈满了,生产者等待");
    condition.await(); // 使用while再次确认 防止虚假唤醒
    }
    ms.push(item);
    log("生产者压入"+ item);
    condition.signal(); // 通知消费者
    } finally {
    lock.unlock();
    }
    }
    // 在栈空的情况下 使当前进程wait
    // 将item取出栈
    // 通知生产者wait进程可放
    E pop() throws InterruptedException {
    try {
    lock.lock();
    while (ms.size() == 0) {
    log("栈为空,消费者等待");
    condition.await();
    }
    E item = ms.pop();
    log("消费者弹出"+item);
    condition.signal();
    return item;
    } finally {
    lock.unlock(); // 解锁
    }
    }
    }

    public class PCproblem2 {
    public static void main(String[] args) {
    MyNewStack<Integer> ms = new MyNewStack(10); // 临界区
    // TODO Auto-generated method stub
    // 1个生产者线程
    Thread producer = new Thread() {
    public void run() {
    ms.log("启动");
    Random r = new Random();
    try {
    while (true) {
    int x = r.nextInt(10);
    ms.push(x);
    Thread.sleep(1000);
    }
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    };
    producer.setName("producer");
    producer.start();
    // 3个消费者线程
    Thread[] consumer = new Thread[3];
    for (int i = 0; i < 3; i++) {
    Thread t = new Thread() {
    public void run() {
    ms.log("启动");
    try {
    while (true) {
    int x = ms.pop();
    ms.log("thousand years later...");
    Thread.sleep(5000);
    }
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    };
    consumer[i] = t;
    t.setName("consumer" + (i + 1));
    t.start();
    }
    }

    }

    8.7 线程池

    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
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    package multipleThread;

    import java.util.LinkedList;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;

    class MyThreadPool {
    int poolSize;
    // 任务容器
    LinkedList<Runnable> tasks = new LinkedList<Runnable>();

    // 10个消费者进程
    public MyThreadPool() {
    poolSize = 10;
    for (int i = 0; i < 10; i++) {
    new ConsumeThread("线程"+i).start();
    }
    }

    // 加入到任务容器中
    public void add(Runnable r) {
    synchronized (tasks) {
    tasks.add(r);
    // 通知wait的消费者进程
    tasks.notifyAll();
    }
    }

    // 子类
    // 消费者线程
    class ConsumeThread extends Thread {
    public ConsumeThread(String name) {
    super(name);
    }
    Runnable task;
    public void run() {
    System.out.println("启动:" + this.getName());
    while (true) { // 启动后一直保持运行状态
    synchronized (tasks) { // 对tasks同步访问
    // 任务容器为空 wait
    while (tasks.isEmpty()) {
    try {
    tasks.wait();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    // 从任务容器中取出任务
    task = tasks.removeLast();
    // 通知生产任务线程继续生产
    tasks.notifyAll();
    }
    System.out.println(this.getName()+"获取到任务,并执行");
    task.run();
    }
    }
    }
    }

    public class ThreadPool {

    private void selfThreadPoolMethods() {
    // 线程数
    // 最大线程数
    // 多余线程被回收的空余时间
    ThreadPoolExecutor tpe = new ThreadPoolExecutor(10,15,60,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());
    for (int i = 0; i < 20; i++) {
    System.out.println(i);
    tpe.execute(new Runnable() {

    @Override
    public void run() {
    // TODO Auto-generated method stub
    System.out.println("do something!");
    try { // 拉长任务执行时间
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    });
    }
    }

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    new ThreadPool().selfThreadPoolMethods();
    System.out.println("end");
    /*
    MyThreadPool mtp = new MyThreadPool();
    int slptime = 1000;
    // 加入任务
    for (int i = 0; i < 100; i++) {
    Runnable r = new Runnable() {
    public void run() {
    System.out.println("do something!");
    try { // 拉长任务执行时间
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    };
    mtp.add(r);
    try {
    slptime = slptime > 100 ? slptime - 100 : slptime;
    Thread.sleep(slptime); // 缩短任务加入间隔
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    */
    }

    }