目录
长字符串逆序,包含空格
Guava:
打印三角形:
Arrays:
双色球系统:
注解:
二叉排序树:
线程池:
File类:
IOStream:
List集合:
Map集合:
动态代理:
反射:
正则表达式:
String:
多线程Thread:
多线程之生产者与消费者:
观察者设计模式:
DOM解析XML:
网络Socket编程:
import java.util.Scanner;
public class TestString2 {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("请输入字符串");
String inputString=scanner.nextLine();
System.out.println("反转后的字符串");
String outputString=reverse(inputString);
System.out.println(outputString);
}
public static String reverse(String str){
int length=str.length();
if (length>100||length<0) {
System.out.println("输入不合法");
return null;
}
StringBuilder stringBuilder=new StringBuilder();
for (int i = length; i > 0 ; i--) {
stringBuilder.append(str.charAt(i-1));
}
return stringBuilder.toString();
}
}
//将任意位数的整数逆序,且去除前位的0
public static int rev(int x){
StringBuilder stringBuilder=new StringBuilder(x+"");
stringBuilder.reverse();
return Integer.valueOf(stringBuilder.toString());
}
public static void getHashMap(String string){
HashMap
//Object用来保存拼接后的数组
//输出数组Arrays.toString(concat(ints, strings));格式为[,,,],字符串没有双引号
//要输出带双引号的字符串,则字符串定义时为"\"a\""即转义双引号
public static Object[] concat(int[] ints,String[] string2){
int length1=ints.length;
int length2=string2.length;
Object[] o=new Object[length1+length2];
for (int i=0;i
public class TestGuava {
/**
* Collect包下集合工具类测试:Collections2,Lists,Sets,Maps,Multisets,Queues,Tables
* 方法都为静态工厂方法如List list=Lists.newArrayList(...elements);
* 强大的新建拥有任意个元素的集合的方法newXXX(...elements)
*/
//过滤器filter():过滤参数1指定集合中的元素e,e以参数2指定规则;遍历输出结果
@Test
public void testFilter(){
List list= Lists.newArrayList("A", "AB","aC","D");
Collection result=Collections2.filter(list, (e)->e.startsWith("A"));
result.forEach(System.out::println);
}
//转换器transform():集合元素的按照参数2指定规则的任意格式转换
@Test
public void testTransform(){
Set timeSet= Sets.newHashSet(20190101L,20180101L,20170101L);
Collection time=Collections2.transform(timeSet, (e)->new SimpleDateFormat("yyyy-MM-dd").format(e));
time.forEach(System.out::println);
}
/**
* Guava:
* 1、基本工具
* 1.1,使用和避免null
* 1.2,前置条件,方法的条件判断、检查
* 1.3,Object方法
* 1.4,排序功能
* 1.5,Throwables异常和错误的传播与检查
* 2、集合
* 不可变集合,防御性编程和性能提升
* 新集合类型,multisets,multimaps,tables,bidirectional maps
* 强大的集合工具类
* 扩展工具类
* 3、缓存
* 4、函数式编程
* 5、并发
* 6、字符串处理
* 分割,连接,填充字符串等
* 7、原生类型的支持
* 8、区间、IO、散列、事件总线、数学运算、反射
*/
}
public class Test01 {
public static void main(String args[]){
//打印直角三角形
for (int i = 1; i < 10; i++) {
for (int j = 9; j > 0; j--) {
if (j<=i)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
//打印等腰三角形
for (int i = 1 ; i < 10; i++) {
//左上角空格
for (int j = i; j < 9; j++) {
System.out.print(" ");
}
//*号
for (int j = 1; j <= 2*i-1; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
import java.util.Arrays;
public class Test02 {
public static void main(String[] args) {
float result0=add(1,2.0f);
float result1=add(1,2);
System.out.println(result0);
System.out.println(result1);
//Arrays API
int[] arr={1,2,3,4,7,8,9,10,5,6};
int key= Arrays.binarySearch(arr,6);
System.out.println(key);
//输出数组:1 2 3 4 5...
for (int i:arr){
System.out.print(i+"\t");
}
//转为字符串输出:[1,2,3,4,5,...],即toString()方法会添加[]和逗号分隔符
System.out.println(Arrays.toString(arr));
//排序
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
//复制
int[] arrCopy0 = Arrays.copyOf(arr,5);
int[] arrCopy1 = Arrays.copyOfRange(arr,2,8);
System.out.println(Arrays.toString(arrCopy0));
System.out.println(Arrays.toString(arrCopy1));
//填充
Arrays.fill(arr,0);
System.out.println(Arrays.toString(arr));
}
public static float add(int a,float b){
return a+b;
}
}
/**
* 双色球:
* 系统产生6个红色球号码,号码为1-33之间不重复数字;1个蓝色球号码,范围1-16
* 用户选择6个不重复号码,1个蓝球号码,分别与系统比较,根据相同个数确定中奖等级
*/
public class Test03 {
public static void main(String[] args) {
int[] userRedBall = new int[6];//用户选择的6个红球号码
int[] systemRedBall = new int[6];//系统产生的6个红球号码
int redBallCount = 0;//用户选择正确的红球个数
int blueBallCount = 0;//用户选择正确的蓝球个数
int userBlueBall = 0;//用户选择的蓝球
int systemBlueBall = 0;//系统产生的蓝球
//用户的红蓝球选择
System.out.println("双色球游戏:请输入您选择的6个不重复红球号码(1-33):");
Scanner input = new Scanner(System.in);
//outer:
for (int i = 0; i < userRedBall.length; i++) {
userRedBall[i] = input.nextInt();
int temp = userRedBall[i];
//范围限制
if (userRedBall[i] > 0 && userRedBall[i] < 34) {//为什么这里不能直接写if(input.nextInt()>0&&input.nextInt()<34)?????
for (int j = 0; j < i; j++) {
//不能选择重复的:将已经输入的前i个元素作为j循环遍历,分别和temp比较
//temp保存下一个输入即input.nextInt(),但temp应向上面那样赋值而不是直接=input.nextInt(),这样会陷入无限循环输入
if (userRedBall[j] == temp) {
System.out.println("您已经选过这个球了。请重新选择:");
//实现重新开始输入的逻辑
//。。。。。。。
System.exit(0);
} else {
}
}
continue;
} else {
System.out.println("您选择红球的号码不在范围内。");
System.exit(0);
}
}
System.out.println("双色球游戏:请输入您选择的1个蓝球号码(1-16):");
userBlueBall = input.nextInt();
System.out.println("-------------------");
if (userBlueBall > 0 && userBlueBall < 17) {
System.out.println("用户所选6个红球号码:" + Arrays.toString(userRedBall));
System.out.println("用户所选1个蓝球号码:" + userBlueBall);
} else {
System.out.println("您选择蓝球的号码不在范围内。");
System.exit(0);
}
System.out.println("---------------------------");
//系统的红蓝球产生
//红球:随机生成1-33之间不重复的6个数字
int[] allRedBall = new int[33];
for (int i = 0; i < allRedBall.length; i++) {
allRedBall[i] = i + 1;
}
randomBall(allRedBall, systemRedBall);//随机6个红球的产生
userBlueBall = new Random().nextInt(16) + 1;//随机一个蓝球的产生
System.out.println("6个红球开奖号码:" + Arrays.toString(systemRedBall));
System.out.println("1个蓝球开奖号码:" + userBlueBall);
System.out.println("-------------------");
//比较系统和用户的球的号码,验证中奖
if (systemBlueBall == userBlueBall) {
blueBallCount = 1;
}
for (int i = 0; i < userRedBall.length; i++) {
for (int j = 0; j < systemRedBall.length; j++) {
if (userRedBall[i] == systemRedBall[j]) {
redBallCount++;
System.out.println("中奖红球号码:" + userRedBall[i]);
break;
}
}
}
if (blueBallCount == 0) {//blueBallCount==0方便测试,否则==1概率太低
switch (redBallCount) {
case 1:
System.out.println(redBallCount + "个红球,六等奖!");
break;
case 2:
System.out.println(redBallCount + "个红球,五等奖!");
break;
case 3:
System.out.println(redBallCount + "个红球,四等奖!");
break;
case 4:
System.out.println(redBallCount + "个红球,三等奖!");
break;
case 5:
System.out.println(redBallCount + "个红球,二等奖!");
break;
case 6:
System.out.println(redBallCount + "个红球,一等奖!");
break;
default:
System.out.println(redBallCount + "个红球,未中奖。");
break;
}
} else {
System.out.println(blueBallCount + "个蓝球,未中奖。");
}
}
//将范围内值作为个数组,产生一个随机值后,将此值与数组最后一个元素交换;然后在除去最后一个元素的数组中产生第二个随机值;
//如此重复;参数1表示产生随机数的范围
public static void randomBall(int[] allBalls, int[] redBalls) {
Random random = new Random();
int allBallsIndex = -1;
for (int i = 0; i < redBalls.length; i++) {
allBallsIndex = random.nextInt(allBalls.length - i);//产生范围内一个随机数作为下标
redBalls[i] = allBalls[allBallsIndex];//范围内下标处的数作为随机数数组
int temp = allBalls[allBallsIndex];
allBalls[allBallsIndex] = allBalls[allBalls.length - 1 - i];
allBalls[allBalls.length - 1 - i] = temp;
}
}
}
package file;
/**
* Annotaion注解
*/
public @interface TestAnnotation {
//定义变量;需要括号;可在定义时设置默认值;否则在调用注解时必须设置变量的值;
public int id();
public String name() default "A";
public int[] number();
}
/**
* 使用注解:通过反射得到注解类,作为getAnnocation()的参数获取变量值,将注解中的值赋给被标注对象,即让注解生效
*/
@TestAnnotation(id = 1,number = {1,2,3})
class TestUseAnnotation{
private int id;
private String name;
private int[] number;
}
package file;
//二叉排序树
public class TestBinaryTree {
public static void main(String[] args) {
TestBinaryTree node = new TestBinaryTree();
node.addData(4);
node.addData(7);
node.addData(98);
node.addData(46);
node.addData(4);
node.addData(2);
node.addData(45);
node.addData(84);
node.print();
}
private Node node;
//数据进来,如果是第一个数,则作为根节点,否则调用节点添加函数
public void addData(int data) {
if (null == node) {
node = new Node(data);
} else {
node.addNode(data);
}
}
//从根节点按照中序遍历打印二叉树
public void print() {
this.node.printNodeData();
}
}
class Node {
private int data;
private Node leftNode;
private Node rightNode;
public Node(int data) {
this.data = data;
}
/*
添加节点:判断进来的数据:
1、当前数据小,应放在节点左边
如果做节点不存在,则以当前数据新建做节点;
否则递归做节点,即继续比较做节点的数据与当前数据,判断当前数据应在左节点的哪边;
2、右边同理
*/
public void addNode(int data) {
if (this.data > data) {
if (null == this.leftNode) {
this.leftNode = new Node(data);
} else {
this.leftNode.addNode(data);
}
} else {
if (null == this.rightNode) {
this.rightNode = new Node(data);
} else {
this.rightNode.addNode(data);
}
}
}
//中序遍历:左-中-右
public void printNodeData() {
if (null != this.leftNode) {
this.leftNode.printNodeData();
}
System.out.print(this.data + " -> ");
if (null != this.rightNode) {
this.rightNode.printNodeData();
}
}
}
package file;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 线程池
*/
public class TestExecutor {
public static void main(String[] args) {
//单线程线程池:一个线程执行完执行另一个线程
ExecutorService es= Executors.newSingleThreadExecutor();
es.execute(new Run());
es.execute(new Run());
//固定大小的线程池
es=Executors.newFixedThreadPool(2);
//可缓存,动态大小
es=Executors.newCachedThreadPool();
//无限大小,周期变换
es=Executors.newScheduledThreadPool(2);
es.shutdown();
}
}
class Run implements Runnable{
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()+"----"+i);
}
}
}
package file;
import java.io.File;
import java.io.IOException;
public class TestFile {
public static void main(String[] args) {
searchFile(new File("C:\\Users\\Administrator\\Desktop\\File"), ".txt");
}
//创建文件
private static void creatNewFile() {
//File file=new File("C:\\Users\\Administrator\\Desktop\\File");
File file = new File("C:" + File.separator + "File" + File.separator + "test.txt");
if (!file.exists()) {
try {
file.createNewFile();//创建文件
} catch (IOException e) {
e.printStackTrace();
}
}
}
//查找文件
private static void searchFile(File targetFile, String endWithName) {
if (null == targetFile)
return;
//如果是目录,遍历所有文件
if (targetFile.isDirectory()) {
File[] files = targetFile.listFiles();
//如果文件中还有文件,递归遍历;慎用
if (null != files) {
for (File file : files) {
searchFile(file, endWithName);
}
}
} else {
String fileName = targetFile.getName().toLowerCase();
System.out.println(fileName);
if (fileName.endsWith(endWithName)) {
System.out.println(targetFile.getAbsolutePath());
}
}
}
}
package file;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Properties;
public class TestIOStream {
public static void main(String[] args) {
}
private static void out(){
File file=new File("c:\\");
try {
OutputStream out=new FileOutputStream(file);
String content="输出的内容";
out.write(content.getBytes());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void in(){
File file=new File("c:\\");
try {
InputStream in=new FileInputStream(file);
byte[] bytes=new byte[1024*10];
int length=-1;
StringBuilder stringBuilder=new StringBuilder();
while ((length=in.read(bytes))!=-1){
stringBuilder.append(new String(bytes));
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void charRead(InputStream inputStream){
Reader reader=new InputStreamReader(inputStream, Charset.forName("UTF-8"));
}
//Properties类:配置文件读取类
private static void readProperties(){
Properties properties=new Properties();
try {
InputStream inputStream=new FileInputStream("cogfig.properties");
properties.load(inputStream);//加载配置文件
//读取配置文件中的信息
String name=properties.getProperty("name");
//。。。
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package file;
import java.util.*;
/**
* List:有序序列集合
*/
public class TestList {
public static void main(String[] args) {
testArrayList();
testHashSet();
}
//ArrayList测试
private static void testArrayList(){
List arrayList=new ArrayList<>();
arrayList.add("a");
arrayList.add("b");
arrayList.add("c");
// arrayList.add(3);
int size=arrayList.size();
for (int i = 0; i < size; i++) {
System.out.println(arrayList.get(i));
}
System.out.println(arrayList.contains("a"));//true
arrayList.remove("c");//removeAll()
String[] array=arrayList.toArray(new String[]{});
}
//LinkedList测试
private static void testLinkedList(){
}
//Vector测试
private static void testVector(){
}
//HashSet测试
private static void testHashSet(){
Set set = new HashSet();
Set set1 = new HashSet();
Set set2 = new HashSet();
set.add("a");
set1.add("b");
set.addAll(set1);
set2.addAll(set);
Integer integer=1;
set2.add(integer);
String[] strings=set.toArray(new String[]{});
for (String string:strings) {
System.out.println(string);
}
for (String str:set) {
System.out.println(str);
}
System.out.println(set2.size());
System.out.println(set2);
for(Object object:set2){
if (object instanceof Integer){
int i=((Integer) object).intValue();
System.out.println(i);
}else if (object instanceof String){
System.out.println(object);
}
}
}
//Iterator迭代器测试
private static void testIterator(Collection collection){
//foreach遍历
for (String string:collection){
System.out.println(string);
}
//Iterator遍历
Iterator iterator=collection.iterator();
while (iterator.hasNext()){
String string=iterator.next();
System.out.println(string);
}
collection=new ArrayList();
collection.add("A");
collection.add("B");
collection.add("C");
}
}
package file;
import java.util.*;
public class TestMap {
public static void main(String[] args) {
testMap();
}
private static void testMap(){
Map map=new HashMap();
map.put(0, String.valueOf(0));
map.put(1, "1");
System.out.println("size:"+map.size());
System.out.println(map.get(0));
//遍历键值对
Set> entrySet=map.entrySet();
for (Map.Entry entry:entrySet){
System.out.println(entry.getKey()+"->"+entry.getValue());
}
//遍历键,通过键得到值
Set keys=map.keySet();
for (Integer integer:keys){
String value=map.get(integer);
System.out.println(integer+"=>"+value);
}
//遍历值
Collection values=map.values();
for (String value:values){
System.out.println(value);
}
System.out.println(map+"----------------"+map.size());
//HashMap和Hashtable可以互转;内容全部清空
map=new Hashtable<>();
map.put(1, "new 1");
System.out.println(map+"--------------"+map.size());
HashMap linkedHashMap=new LinkedHashMap();//子类使用双重链表维护元素顺序
//Collections工具类测试
List list=new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("ab");
list.add("ac");
Collections.reverse(list);//反序
System.out.println(list);
Collections.shuffle(list);//随机排序
System.out.println(list);
Collections.sort(list);//排序
System.out.println(list);
Collections.swap(list, 0, 1);//交换
System.out.println(list);
Collections.rotate(list, 2);//旋转,参数2表示移动个数
System.out.println(list);
System.out.println(Collections.min(list));
List synchronizedList=Collections.synchronizedList(list);//使其线程安全
}
}
package file;
import org.junit.Test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class TestProxy implements People{
@Override
public void doSomething() {
try {
System.out.println(Class.forName("E:\\IntelliJ IDEA\\tests\\src\\file\\TestProxy.java")+"即本类doSomething");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
/**
* 代理类测试:创建被代理接口/对象
*/
interface People {
public void doSomething();
}
/**
* 代理类:用于动态生成代理类对象
*/
class CreateProxy implements InvocationHandler {
private Object proxyTarget;//被代理类的对象
//创建代理类对象
public Object createProxy(Object proxyTarget){
this.proxyTarget=proxyTarget;
//参数1获取被代理类加载器,参数2获取被代理类所以实现的接口,参数3位当前代理类对象
Object proxy=Proxy.newProxyInstance(proxyTarget.getClass().getClassLoader(), proxyTarget.getClass().getInterfaces(), this);
return proxy;
}
//代理类对象执行的代理操作/方法
//proxy指代理类对象,method指被代理对象的方法,args指方法参数列表
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("请求代理类来代理");
method.invoke(proxy, args);//被代理对象调用invoke方法即交付代理类来执行
System.out.println("完成代理交付");
return null;
}
}
class TestProxy2{
@Test
public void test1(){
CreateProxy proxy=new CreateProxy();//代理工具
People user=new TestProxy();//原接口,被代理
People proxyUser= (People) proxy.createProxy(user);//完成代理交付
proxyUser.doSomething();//被代理后做事儿
}
}
package file;
import org.junit.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
/**
* 类的获取之反射
*/
public class TestRefletct {
public static void main(String[] args) {
}
@Test
public void getClazz(){
//通过Object的getClass()方法
User user=new User(1,"a");
Class clazz=user.getClass();
System.out.println("OK1");
//通过Object的class静态属性
clazz=User.class;
System.out.println("OK2");
//通过Class的静态方法反射
try {
clazz=Class.forName("file.User");
System.out.println("OK3");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//反射得到Class,获取类的构造方法,参数,属性等信息
@Test
public void getObject(){
try {
Class clazz=Class.forName("file.User");
User user= (User) clazz.newInstance();
Constructor[] constructors=clazz.getConstructors();
//构造器个数
int length=constructors.length;
System.out.println(length);
for (int i = 0; i < length; i++) {
//构造器名字及参数个数
System.out.println(constructors[i].getName());
System.out.println(constructors[i].getParameterCount());
}
//通过构造器实例化对象
Constructor constructor=clazz.getConstructor(int.class,String.class);
user= (User) constructor.newInstance(2,"b");
System.out.println(user);
//获取属性
Field[] fields=clazz.getFields();
fields=clazz.getDeclaredFields();
int fieldsLength=fields.length;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {//安全权限异常,反射时调用了private方法
e.printStackTrace();
} catch (InstantiationException e) {//对象实例化异常
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {//调用的方法内部抛出异常而未捕获时,由此异常接收
e.printStackTrace();
}
}
}
class User{
private int id;
private String name;
public User() {
}
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public static void main(String[] args) {
}
}
package file;
/**
* 正则表达式
*/
import org.junit.Test;
public class TestRegex {
@Test
public void test(){
//匹配电话号码,规则:3-4位的数字,-,7-8位的数字
String phoneNumber="010-1122334";
boolean isPhoneNumber=phoneNumber.matches("\\d{3,4}-\\d{7,8}");
System.out.println(isPhoneNumber);
//匹配手机号码:首位为1,第二位为3-9中任一一个,后面是9位的任意数字
String cellPhoneNumber="13881234567";
boolean isCellPhoneNumber=cellPhoneNumber.matches("[1][3-9]\\d{9}");
System.out.println(isCellPhoneNumber);
//匹配用户名:字母开头(+表示至少出现一次),数字、字母或下划线(*表示0次或多次)组成
String userName="afd9768698_9";
boolean isUserName=userName.matches("[a-zA-Z]+[\\W|_]*");
System.out.println(isUserName);
//匹配IP地址:4个1-3位0-255之间的数字,.连接
String ip="127.0.0.1";
boolean isIP=ip.matches("\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}");
System.out.println(isIP);
//匹配网址:http://www.xxx.com
String url="http://www.baidu.com";
//boolean isURL=url.matches("http:")
}
}
package file;
/**
* String,StringBuffer,StringBuilder测试
*/
public class TestString {
public static void main(String[] args) {
String string01 = "张";//涉及到栈和字符串常量池;推荐方式
String string02 = new String("张");//涉及到栈,堆,常量池
String string03 = "张";
System.out.println(string01 == string02);//false
System.out.println(string01.equals(string02));//true;字符串重写了equals()方法
System.out.println(string01 == string03);//true
System.out.println("==========================================");
//如果在编译期可以确定值,那么则使用已有值,否则在运行期创建新的对象
//方法返回值在运行期确定,即使方法返回值被赋给final
String string04 = "a";
String string05 = string04 + 1;//运行期间才会确定值;但是如果string04是final修饰,即常量替换,则string05在编译期可以确定
String string06 = "a1";//编译期确定
System.out.println(string05 == string06);//false
String string07 = "dggafghfdh111111111113242353535g";
System.out.println(string07.replaceAll("\\d", "*"));
}
public void print() {
System.out.println("测试字符串");
}
}
package file;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TestThread {
public static void main(String[] args) {
/* Runnable runnable = new DaemonRunnable();
Thread daemonThread = new Thread(runnable);
daemonThread.setDaemon(true);//设置线程为守护线程
daemonThread.start();//开启守护线程
for (int i = 0; i < 10; i++) {
System.out.println("这是主线程");
try {
//当主线程休眠时,执行守护线程;
//当主线程执行完,没有了用户线程,守护线程也停止
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}*/
Runnable runnable1=new SynchronizedThread();
Thread thread1=new Thread(runnable1);
Thread thread2=new Thread(runnable1);
thread1.start();
thread2.start();
}
}
/**
* 守护线程:当系统没有用户线程时,守护线程自动停止执行
*/
class DaemonRunnable implements Runnable{
@Override
public void run() {
System.out.println("这是一个守护线程");
}
}
/**
* 线程同步:资源共享
*/
class SynchronizedThread implements Runnable{
private int ticket=10;//10张票
private Object object=new Object();//用作同步锁的对象,任何同步线程执行前需要检查该锁,执行完后释放该锁
//互斥锁:灵活的同步锁来控制同步,lock()加锁,unlock()释放锁,
Lock lock=new ReentrantLock();
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (ticket>0){
synchronized (object){
System.out.println("剩余票数:"+ticket+"张");
try {
Thread.sleep(1000);
//sleep()让出CPU给其他线程执行,但是不会释放对象锁
//所以其他同步线程其实没有获得对象锁,没有执行权,这段时间被干耗
} catch (InterruptedException e) {
e.printStackTrace();
}
ticket--;
}
}
}
}
}
package file;
/**
* 食物
*/
public class Food {
private String name;
private String desc;
private boolean flag=true;
public Food() {
}
public Food(String name, String desc) {
this.name = name;
this.desc = desc;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public String toString() {
return "Food{" +
"name='" + name + '\'' +
", desc='" + desc + '\'' +
'}';
}
/**
* 生产食物:执行过程
* flag==true即可生产,则设置name,休眠1秒,然后设置desc;
* 将flag设置为false,唤醒其他线程,即通知消费线程可执行了
* 如果不同步,则在休眠时多次执行此方法后设置的desc会在不同对象间混乱
* 否则,本线程等待其他线程执行完并被唤醒
*/
public synchronized void producterFood(String name,String desc){
//不生产,等待被唤醒;wait()让出CPU时间片并释放对象锁
if (false==flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.setName(name);
System.out.println("已经生产食物-"+this.getName());
try {
Thread.sleep(1000);//进入休眠,让出CPU时间片但不释放对象锁
} catch (InterruptedException e) {
e.printStackTrace();
}
this.setDesc(desc);
System.out.println(this.getName()+"-是-"+this.getDesc()+"---------------");
flag=false;
this.notify();//唤醒随机一个线程
}
//消费食物
public synchronized void constomerFood(){
if (flag==true){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("上菜!");
System.out.println(this.getName()+"->"+this.getDesc());
flag=true;
this.notify();
}
}
package file;
/**
* 服务员等待厨师做完美食(生产者线程)后上菜(消费者线程)
*/
public class TestThread2 {
public static void main(String[] args) {
Food food=new Food();
Producter producter=new Producter(food);
Customer customer=new Customer(food);
Thread thread0=new Thread(producter);
Thread thread1=new Thread(customer);
thread0.start();
thread1.start();
}
}
//生产者:模拟生产20份食物
class Producter implements Runnable{
private Food food;
public Producter(Food food){
this.food=food;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if (i%2==0){
food.producterFood("麻辣鸡丝","鸡丝!");
}else {
food.producterFood("麻婆豆腐", "豆腐!");
}
}
}
}
//消费者:模拟输出10份食物
class Customer implements Runnable{
private Food food;
public Customer(Food food){
this.food=food;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
food.constomerFood();
}
}
/**
* 开启两个线程,问题:
* 1、数据共享但没实现线程同步,在sleep()阶段出现其他线程的执行而导致对象属性错乱,即即使有sleep()也要执行完
* 2、两个线程的执行必须有先后顺序即一定先生产后消费,所以为Food对象设置互斥flag,为true时需要生产即不能消费,false是可以消费
*/
}
package file.SubjectAndObserver;
/**
* 被观察者
*/
public interface MessageSubject {
//注册观察者、移除、通知所有观察者
public void registerObserver(Observer observer);
public void removeObserver(Observer observer);
public void notifyObservers();
}
package file.SubjectAndObserver;
/**
* 观察者
*/
public interface Observer {
//跟新消息
public void update(String message);
}
package file.SubjectAndObserver;
import java.util.ArrayList;
public class Message implements MessageSubject {
private String message;
//维护所有观察者列表
private ArrayList observerArrayList=new ArrayList<>();
public void setMessage(String message) {
this.message = message;
notifyObservers();
}
@Override
public void registerObserver(Observer observer) {
observerArrayList.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observerArrayList.remove(observer);
}
@Override
public void notifyObservers() {
for (int i = 0; i < observerArrayList.size(); i++) {
Observer observer=observerArrayList.get(i);
observer.update(message);
}
}
}
package file.SubjectAndObserver;
public class User implements Observer {
@Override
public void update(String message) {
System.out.println(this+"---"+message);
}
}
package file.SubjectAndObserver;
public class Test {
@org.junit.Test
public void test(){
Message message=new Message();
Observer observer0=new User();
Observer observer1=new User();
Observer observer2=new User();
message.registerObserver(observer0);
message.registerObserver(observer1);
message.registerObserver(observer2);
message.setMessage("我发的消息,还有谁没收到?");
}
}
001
138001
002
138002
package file.XmlAndDom;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.beans.XMLEncoder;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
public class TestDomAndXml {
//解析XML文件为对象
@Test
public void test() {
//创建工厂
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
try {
//工厂生产解析器
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
//解析对象作为流被解析为DOM文档对象
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("file/XmlAndDom/person.xml");
Document document = documentBuilder.parse(in);
//从DOM中读取数据,返回节点集合对象
NodeList person = document.getElementsByTagName("person");
int nodePersonLength = person.getLength();
System.out.println(nodePersonLength);
//构建Person对象集合
ArrayList persons = new ArrayList<>();
Person p = null;
for (int i = 0; i < nodePersonLength; i++) {
//遍历DOM对象中的元素,每个元素作为一个节点,用来构建bean对象
Node personNode = person.item(i);
p = new Person();
String personId = personNode.getAttributes().getNamedItem("personId").getNodeValue();
p.setId(personId);
//获取子节点
NodeList childNodes = personNode.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node childNode = childNodes.item(j);
String nodeName = childNode.getNodeName();
if ("name".equals(nodeName)) {
p.setName(childNode.getFirstChild().getNodeValue());
} else if ("tel".equals(nodeName)) {
p.setTel(childNode.getFirstChild().getNodeValue());
}
}
persons.add(p);
}
System.out.println(Arrays.toString(persons.toArray()));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//将对象写入到XML文件:XMLEncoder
@Test
public void test1() {
try {
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream("file/XmlAndDom/test.xml"));
XMLEncoder xmlEncoder = new XMLEncoder(outputStream);
Person person = new Person();
person.setId("E03");
person.setName("003");
person.setTel("003");
xmlEncoder.writeObject(person);
xmlEncoder.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
package file.Echo;
import java.io.Serializable;
/**
* 数据包
*/
public class Message implements Serializable {
private String from;//发送者
private String to;//接受者
private int type;//类型
public final static int messageType1=1;//消息类型:客户端登录
public final static int messageType2=2;//消息类型:客户端发送消息
private String message;//内容
public Message() {
}
public Message(String from, String to, int type, String message) {
this.from = from;
this.to = to;
this.type=type;
this.message = message;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
@Override
public String toString() {
return "Message{" +
"from='" + from + '\'' +
", to='" + to + '\'' +
", to='" + type + '\'' +
", messageType1=" + messageType1 +
", messageType2=" + messageType2 +
", message='" + message + '\'' +
'}';
}
}
package file.Echo;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
/**
* 客户端
*/
public class EchoClient {
public static void main(String[] args) {
EchoClient echoClient =new EchoClient();
//echoClient.sendMessage();
echoClient.sendMessage2();
}
private void sendMessage(){
try {
Socket socket=new Socket("localhost",6666);
BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream printStream=new PrintStream(new BufferedOutputStream(socket.getOutputStream()));
printStream.println("客户端请求连接你啦!");
printStream.flush();
String message=br.readLine();
System.out.println(message);
printStream.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendMessage2(){
Scanner scanner=new Scanner(System.in);
try {
Socket socket=new Socket("localhost",6666);
ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
System.out.println("请输入名称:");
String name=scanner.nextLine();
Message message=new Message(name, null, 1, null);
outputStream.writeObject(message);
message= (Message) inputStream.readObject();
System.out.println(message.getMessage()+","+message.getFrom());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
package file.Echo;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 应答系统:服务器接收客户端发送来的字符串后回发给客户端
* 服务器端
*/
public class EchoServer {
public static void main(String[] args) {
EchoServer echoServer = new EchoServer();
//echoServer.getMessage();
echoServer.doUserClientThreads();
}
//建立服务器并获取客户端
private void getMessage() {
try {
//建立服务器端并接受服务器请求
ServerSocket serverSocket = new ServerSocket(6666);
System.out.println("服务器已经启动,等待接收客户端信息。");
Socket socket = serverSocket.accept();
System.out.println(serverSocket.getInetAddress().getHostAddress() + "客户端连接成功");
//通过输入流读取数据;没有数据传出则阻塞
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = br.readLine();
System.out.println(message);
//通过输出流返回信息给客户端
PrintStream printStream = new PrintStream(new BufferedOutputStream(socket.getOutputStream()));
printStream.println("ECHO " + message);
printStream.flush();
printStream.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//服务器处理多个客户端线程
//主线程开辟(使用线程池)多个子线程来分别处理每一个客户端,而主线程一直保持等待客户端连接的状态
private void doUserClientThreads() {
ExecutorService executorService = Executors.newFixedThreadPool(3);
try {
ServerSocket serverSocket = new ServerSocket(6666);
System.out.println("服务器已经启动,等待客户端连接");
while (true) {
Socket socket = serverSocket.accept();
System.out.println(socket.getInetAddress().getHostAddress());
//线程池管理线程
executorService.execute(new UserClientThread(socket));
}
} catch (IOException e) {
e.printStackTrace();
}
}
//客户端与客户端之间的通信:通过服务器中转数据包
//数据包需要包含信息:发送者信息,接受者信息,消息内容及类型
private void transitMessage() {
}
}
/**
* 多个客户端线程与服务器的通信:
*/
class UserClientThread implements Runnable {
private Socket clientSocket;//客户端线程
public UserClientThread(Socket socket) {
this.clientSocket = socket;
}
@Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
PrintStream printStream = new PrintStream(new BufferedOutputStream(this.clientSocket.getOutputStream()));
String message = br.readLine();
System.out.println(message);
printStream.println("客户端请求连接" + message);
printStream.flush();
printStream.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 多个客户端线程之间的通信
*/
class ClientToClient implements Runnable {
private String clientName;
private Socket userSocket;
Vector clientThreads;//客户端线程集合
private boolean flag = true;
private ObjectInputStream inputStream;
private ObjectOutputStream outputStream;
public ClientToClient(String name, Socket socket, Vector clientThreads) {
this.clientName=name;
this.userSocket = socket;
this.clientThreads = clientThreads;
clientThreads.add(this);//将当前客户端线程添加进集合
}
@Override
public void run() {
System.out.println("客户端" + userSocket.getInetAddress().getHostAddress() + "已连接服务器!");
try {
inputStream = new ObjectInputStream(userSocket.getInputStream());
outputStream = new ObjectOutputStream(userSocket.getOutputStream());
while (flag) {
Message message = (Message) inputStream.readObject();
int type = message.getType();
switch (type) {
case Message.messageType1:
clientName=message.getFrom();
System.out.println(clientName+" 客户端登录");
message.setMessage("欢迎 "+clientName);
outputStream.writeObject(message);
break;
case Message.messageType2:
String to=message.getTo();
ClientToClient clientToClient;
int size=clientThreads.size();
for (int i = 0; i < size; i++) {
clientToClient=clientThreads.get(i);
if (to.equals(clientToClient.clientName)&&clientToClient!=this){
clientToClient.outputStream.writeObject(message);
break;
}
}
System.out.println("客户端发送消息");
break;
//default:
}
}
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}