大学课程-Java-1-12章书籍正文代码编写

  • by
一.

数组
二.类与对象的基本概念

类函数调用测试
可变长变量测试
get
构造方法
枚举类型
枚举类型的默认方法
三.类的方法

if
swith
for
while
do while
break
continue
异常处理
方法重载
在方法中执行脚本

四.类的重用

类的继承
类的属性隐藏和覆盖
方法覆盖
equals
终结类final
终结方法final
抽象类abstract
抽象方法abstract
泛型
fanxing测试
indexOf
StringBuffer
数学类

一.

数组

package test;

public class MyArry {
	public static void main(String[] args) {
		
		//输出hello world
		System.out.println("Hello world");
		
		//一维数组
		int myArray[];
		myArray=new int[10];
		myArray[0]=0;
		myArray[1]=1;
		for(int i=0;i<myArray.length;i++) {
			System.out.println(myArray[i]);
		}
		
		//二维数组
		int myArray2[][];
		myArray2=new int[4][5];
		int[] x={1,2,3};
		int[] y={3,4,5};
		myArray2[1]= x;
		myArray2[2]= y;
		
		for(int i=0;i<myArray2.length;i++) {
			for(int j=0;j<myArray2[i].length;j++) {
				System.out.println(myArray2[i][j]);
			}
		}
		
		//
		
	}

}

二.类与对象的基本概念

类函数调用测试
可变长变量测试
get
构造方法
枚举类型
枚举类型的默认方法

package second;


//类与对象的基本概念

public class test1{
	private static String user;
	private static String pass;
	public static void main(String[] args) {
		
		//类函数调用测试
		Circle x=new Circle();
		System.out.println("x: "+x.PI);
		System.out.println("Circle: "+Circle.PI);
		
		//可变长变量测试
		print_test y=new print_test();
		y.print_test("Hello");
		y.print_test("Hello","world");
		
		//get
		System.out.println(getuser());
		System.out.println(user);
		
		//构造方法
		test123 myTest123=new test123();
		System.out.println("aaa: "+myTest123.aaa);
		myTest123.bbb=123;
		System.out.println("bbb: "+myTest123.bbb);
		
		//枚举类型
		getScore(Score.english);
		
		//枚举类型的默认方法
		for(Score s:Score.values()) {
			System.out.println(s);
			System.out.println("getpoint: "+s.getPoint());
		}
		Score s=Score.valueOf("math");
		System.out.println(s.toString());
		System.out.println(s.ordinal());
		s.setPoint(92.0f);
		System.out.println("setpoint->getpoint: "+s.getPoint());
		
	}
	
	
	//bank() example()
	public void Bank (String initname,float initbal) {
		String ownername = initname;
		float accountnumber = initbal;
	}
	public void example() {
		
	}
	
	//get
	public static String getuser() {
		return user;
	}
	//set
	public void setuser(String user) {
		this.user=user;
	}
	
	//枚举类型
	public static void getScore(Score s) {
		switch (s) {
		case chinese:
			System.out.println("chinese");
			break;
		case math:
			System.out.println("math");
			break;
		case english:
			System.out.println("english");
			break;
		default:
			break;
		}
		
	}
	
	//注解
	//@Deprecated
	//@SuppressWarnings
	@Override
	public String toString() {
		return "";
	}
	
	
	
}



//类函数调用测试类
class Circle {
	static double PI=3.1415926;
	int radius;
}

//可变长变量测试类
class print_test{
public void print_test(String... args) {
	for(int i=0;i<args.length;i++) {
		System.out.println(i+": "+args[i]);
		}
	}
}

class test123{
	String aaa;
	int bbb;
}

//枚举类
enum Score{
	chinese,
	math,
	english;
	private float point;
	private Score() {
		// TODO Auto-generated constructor stub
		point=0.0f;
	}
	private Score(float p) {
		this.point=p;
	}
	float getPoint() {
		return point;
	}
	void setPoint(float point) {
		this.point=point;
	}
};

三.类的方法

if
swith
for
while
do while
break
continue
异常处理
方法重载
在方法中执行脚本

package third;


import javax.script.*;
import java.io.File;

//类的方法

public class test {
	public static void main(String[] args) throws ScriptException {
		int i=1;
		int j=2;
		
		//if
		if(i==1) {
			System.out.println("i==1");
		}
		else if (i==2) {
			System.out.println();
		}
		
		//swith
		switch (j) {
		case 2:
			System.out.println("j==2");
			break;
		default:
			System.out.println("no j");
			break;
		}
		
		//for
		for(int x = 0;x<=3;x++) {
			System.out.println(x);
		}
		
		//while
		while(j==3) {
			System.out.println("while: "+j);
		}
		
		//do while
		do {
			j=j+1;
		} while (j==3);  //为真再执行条件
		System.out.println("do while: "+j);
		
		
		//break
		
		//continue
		
		//异常处理
		try {
			
		}catch (Exception e) {
			// TODO: handle exception
		}finally {
			
		}
		
		//方法重载
		rec(1);
		rec("1");
		
		//在方法中执行脚本
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine=manager.getEngineByName("JavaScript");
		File f=new File("1.txt");
		System.out.println(f.getAbsolutePath());
		//File->JavaScript
		engine.put("file", f);  //脚本变量file
		engine.eval("print(file.getAbsolutePath())");
		//JavaScript->File
		File f1=(File)engine.get("file");
		System.out.println(f1.getAbsolutePath());
	}
	public static void rec(int i) {
		System.out.println("int i");
	}
	public static void rec(String i) {
		System.out.println("string i");
	}
}

四.类的重用

类的继承
类的属性隐藏和覆盖
方法覆盖
equals
终结类final
终结方法final
抽象类abstract
抽象方法abstract
泛型
fanxing测试
indexOf
StringBuffer
数学类

package fourth;

import java.awt.List;
import java.util.ArrayList;

//类的重用

public class test {
	public static void main(String[] args) {
		
		//类的继承
		test2 xTest2=new test2();
		xTest2.aaa=100;
		xTest2.ccc="ccc";
		System.out.println(xTest2.aaa);
		System.out.println(xTest2.ccc);
		
		//类的属性隐藏和覆盖
		test2 xTest21=new test2();
		xTest21.test2_method();	
		
		//方法覆盖
		xTest21.method_over();
		
		//equals
		
		//终结类final
		
		//终结方法final
		
		//抽象类abstract
		
		//抽象方法abstract
		
		//泛型
		/*
		ArrayList arrayList = new ArrayList();
		arrayList.add("aaaa");
		arrayList.add(100);
		for(int i = 0; i< arrayList.size();i++){
		    String item = (String)arrayList.get(i);
		    System.out.println("泛型测试item = " + item);
		}
		//会出现错误
		Exception in thread "main" java.lang.ClassCastException: 
		java.lang.Integer cannot be cast to java.lang.String
		at fourth.test.main(test.java:41)
		*/
		ArrayList<String> stringArrayList = new ArrayList<String>();
		ArrayList<Integer> integerArrayList = new ArrayList<Integer>();

		Class classStringArrayList = stringArrayList.getClass();
		Class classIntegerArrayList = integerArrayList.getClass();

		if(classStringArrayList.equals(classIntegerArrayList)){
			System.out.println("泛型测试类型相同");
			System.out.println(classStringArrayList);
		}
		
		//fanxing测试
		fanxing<String> getfanxingstring=new fanxing<String>("fanxingtest");
		fanxing<Integer> getfanxingint=new fanxing<Integer>(12345);
		System.out.println(getfanxingstring.getkey());
		System.out.println(getfanxingint.getkey());
		
		//indexOf
		//StringBuffer
		//数学类
	}
}

class fanxing<F> {
	private F key;
	public fanxing(F key) {  //外部类型决定F类型
		this.key=key;
	}
	public F getkey() { //返回值类型由外部确定
		return key;
	}
		
}

class test1{
	public int aaa;
	public String bbb;
	protected int test1num;
	protected String test1string;
	
	public test1(){
		this(0,"");
	}
	public test1(int test1_num,String test1_string) {
		test1num=test1_num;
		test1string=test1_string;
	}
	public void test1_method() {
		System.out.println("test2->test1");
	}
	public void method_over() {
		System.out.println("test1 method_over");
	}
}

class test2 extends test1{
	public String ccc;
	protected int test2num;
	protected String test2string;
	
	public test2(){
		this(0,"");
	}
	public test2(int i, String j) {
		// TODO Auto-generated constructor stub
		test2num=i;
		test2string=j;
	}
	public void test2_method() {
		super.test1_method();
	}
	public void method_over() {
		super.method_over();
		System.out.println("test2 method_over");
	}
}

class test3 extends test2{
	float ddd;
}

大学课程-Java-5-6章书籍正文代码编写

第五章:接口和多态
接口功能测试
接口多继承
塑型
动态绑定
多态
构造方法与多态
内部类

第六章:输入输出
课本
工具类util中Scanner方法读取
文件
读取文件
文件复制
写二进制文件
读取二进制文件
File类创建文件
压缩文件处理
写压缩文件
读压缩文件
从gz文件读取并写入D:\2.txt
zip文件解压出来
对象序列化
正确地保存和恢复对象的状态
序列化写入
序列化读取

第五章:接口和多态

package fifth;

import second.test1;

//接口和多态

public class test {
	public static void main(String[] args) {
		
		//接口功能测试
		Circle xCircle=new Circle(2.0);
		System.out.println(xCircle.area());
		Rectangle xRectangle=new Rectangle(12, 3);
		System.out.println(xRectangle.area());
		
		//接口多继承
		
		//塑型
		
		//动态绑定
		
		//多态
		
		//构造方法与多态
		test4 xTest4=new test4();
		test5 xTest5=new test5();
		
		//内部类
		test2 xTest2=new test2();
		test2.test2_line xLine=xTest2.new test2_line();
	}
}

//多态和构造方法
class test1{
	public test1() {
		// TODO Auto-generated constructor stub
		System.out.println("test1");
	}
}

//内部类
class test2{
	public test2() {
		// TODO Auto-generated constructor stub
		System.out.println("test2");
	}
	class test2_line{
		public test2_line() {
			// TODO Auto-generated constructor stub
			test2 xTest2=new test2();
		}
	}
}

class test3{
	public test3() {
		// TODO Auto-generated constructor stub
		System.out.println("test3");
	}
}

class test4 extends test1{
	public test4() {
		// TODO Auto-generated constructor stub
		System.out.println("test4");
	}
}

class test5 extends test4{
	public test5() {
		// TODO Auto-generated constructor stub
		System.out.println("test5");
	}
}

//接口Shape2D
interface Shape2D{
	double pi=3.14;
	double area();
}

interface Color{
	void setColor(String string);
}


//继承多接口
class test123 implements Shape2D,Color{
	
	String color;
	double wigth;
	public test123(String c,double w) {
		color=c;
		wigth=w;
	}
	@Override
	public void setColor(String string) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public double area() {
		// TODO Auto-generated method stub
		return 0;
	}
	
}

//
class Circle implements Shape2D{
	double radius;
	public Circle(double r) {
		radius = r;
	}
	@Override
	public double area() {
		// TODO Auto-generated method stub
		return (pi*radius*radius);
	}
}
//
class Rectangle implements Shape2D{
	int width,height;
	
	public Rectangle (int w,int h) {
		width=w;
		height=h;
	}
	
	@Override
	public double area() {
		// TODO Auto-generated method stub
		return (width*height);
	}
	
}


interface Shape extends Shape2D{
	double aaa();
}







第六章:输入输出

package sixth;

import java.awt.TexturePaint;
import java.awt.print.Printable;
import java.io.*;
import java.util.Scanner;
import java.util.zip.*;

import javax.sound.sampled.Line;

//第六章 输入输出
public class test {
	public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
		
		/*
		//课本
		//BufferedReader提高效率 InputStreamReader字节到字符 System.in原始字节流
		BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
		
		String s;
		while((s=in.readLine()).length()!=0) {
			System.out.println("out: "+s);
		}
		
		//工具类util中Scanner方法读取
		Scanner sc=new Scanner(System.in);
		String s1=sc.nextLine(); //nextint
		System.out.println(s1);
		
		//文件
		String filename="D:\\2.txt";
		FileWriter writer=new FileWriter(filename);
		writer.write("hello\n");
		writer.write("world");
		writer.close();
		
		
		//读取文件
		String filename="D:\\2.txt";
		String line;
		BufferedReader in=new BufferedReader(new FileReader(filename));
		line=in.readLine();  //读取一行
		while (line!=null) {
			System.out.println(line);
			line=in.readLine();
		}
		in.close();
		
		//文件复制	
		if(args.length==2) {
			
		}
		test aTest=new test();
		aTest.copy("D:\\1.txt", "D:\\2.txt");
		
		//写二进制文件
		//DataOutputStream
		String filename = "D:\\3.txt";
		int value0=255,value1=0,value2=-1;
		//DataOutputStream outputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));
		DataOutputStream outputStream = new DataOutputStream(new FileOutputStream(filename));
		System.out.println(outputStream.size());
		outputStream.writeInt(value0);
		System.out.println(outputStream.size());
		outputStream.writeDouble(32.9);
		System.out.println(outputStream.size());
		outputStream.writeInt(value2);
		System.out.println(outputStream.size());
		outputStream.close();
		
		//读取二进制文件
		//DataInputStream readInt
		//InputStream
		FileInputStream fileInputStream=new FileInputStream("D:\\2.txt");
		int cString;
		while ((cString=fileInputStream.read())!=-1) {
			System.out.write(cString);
			//System.out.println(cString);
		}
		fileInputStream.close();
		
		//File类
		//File类创建文件
		File xFile=new File("D:\\4.txt");
		if(xFile.exists()) {
			xFile.delete();
		}
		else{
			xFile.createNewFile();
		}
		
		
		//压缩文件处理
		//写压缩文件
		FileInputStream aaa=new FileInputStream("D:\\1.txt");
		GZIPOutputStream gzipOutputStream=new GZIPOutputStream(new FileOutputStream("D:\\1.gz"));
		int c;
		while((c=aaa.read())!=-1) {
			gzipOutputStream.write(c);
		}
		aaa.close();
		gzipOutputStream.close();
		
		//读压缩文件
		BufferedReader in=new BufferedReader(new InputStreamReader(new GZIPInputStream(
				new FileInputStream("D:\\1.gz"))));
		String s;
		while((s=in.readLine())!=null) {
			System.out.println(s);
		}
		in.close();
		
		
		//从gz文件读取并写入D:\\2.txt
		int c;
		GZIPInputStream inputStream=new GZIPInputStream(new FileInputStream("D:\\1.gz"));
		FileOutputStream outputStream=new FileOutputStream("D:\\2.txt");
		while((c=inputStream.read())!=-1) {
			outputStream.write(c);
		}
		outputStream.close();
		inputStream.close();
		
		//zip文件解压出来
		ZipUtils xUtils=new ZipUtils();
		xUtils.unzip("D:\\1.zip");
		
		
		//对象序列化
		//正确地保存和恢复对象的状态
		Book xBook=new Book(123, "user");
		//xBook.test();
		
		//写入
		ObjectOutputStream ooStream=new ObjectOutputStream(new FileOutputStream("D:\\book.dat"));
		ooStream.writeObject(xBook);
		ooStream.close();
		
		//读取
		//xBook=null;
		ObjectInputStream oInputStream=new ObjectInputStream(new FileInputStream("D:\\book.dat"));
		Book yBook=new Book(0, null);
		yBook=(Book)oInputStream.readObject();
		oInputStream.close();
		System.out.println(yBook.id);
		*/
		
		
		
	}
	
	BufferedReader sourece;
	BufferedWriter dest;
	String line;
	String sourceName,destName;
	private static DataOutputStream outputStream;
	//打开文件
	private boolean openFiles()throws IOException{
		System.out.println("openfile start:");
		sourece=new BufferedReader(new FileReader((sourceName)));
		dest=new BufferedWriter(new FileWriter((destName)));
		return true;
	}
	//复制文件
	private boolean copyFiles() throws IOException {
		line=sourece.readLine();
		while(line!=null) {
			System.out.println(line);
			dest.write(line);
			dest.newLine();
			line=sourece.readLine();
		}
		return true;
	}
	//关闭文件
	private boolean closeFiles() {
		boolean retVal=true;
		try {
			sourece.close();
		}
		catch (Exception e) {
			// TODO: handle exception
			retVal=false;
		}
		try {
			dest.close();
		}
		catch (Exception e) {
			// TODO: handle exception
			retVal=false;
		}
		return retVal;
		
	}
	
	//
	public boolean copy(String src,String dst) throws IOException {
		sourceName=src;
		destName=dst;
		System.out.println("copy start:");
		return openFiles()&&copyFiles()&&closeFiles();
	}
	
}


//代码来自:https://www.cnblogs.com/tonghun/p/7189227.html
class ZipUtils{
	private String basePath;
	public void unzip(String unzip) throws IOException {
		File file = new File(unzip);
	    basePath = file.getParent();//得到解压缩文件根目录的文件夹名,保存文件夹存在
	    FileInputStream fis = new FileInputStream(file);
	    ZipInputStream zis = new ZipInputStream(fis); //
	    unzip(zis);
}

	private void unzip(ZipInputStream zis) throws IOException {
		ZipEntry entry = zis.getNextEntry();//得到所有文件名路径  如:1/1.txt 1/2.txt
		System.out.println(entry);
	    if (entry != null) {
	    	//其实 File.separator 的作用相当于 ' \  '
	        File file = new File(basePath + File.separator + entry.getName());
	        if (file.isDirectory()) {
	            // 可能存在空文件夹
	            if (!file.exists())
	                file.mkdirs();
	            unzip(zis);
	        } else {
	            File parentFile = file.getParentFile();
	            if (parentFile != null && !parentFile.exists())
	                parentFile.mkdirs();
	            FileOutputStream fos = new FileOutputStream(file);// 输出流创建文件时必须保证父路径存在
	            int len = 0;
	            byte[] buf = new byte[1024];
	            while ((len = zis.read(buf)) != -1) {
	                fos.write(buf, 0, len);
	            }
	            fos.flush(); //
	            fos.close();
	            zis.closeEntry();
	            unzip(zis);
	        }
	    }
	}

}

class Book implements Serializable{
	int id;
	String name;
	public Book(int id,String name) {
		this.id=id;
		this.name=name;
	}
	public void test() {
		System.out.println(this.id);
		System.out.println(this.name);
	}
}










2019.9.6

大学课程-Java-7-8章书籍正文代码编写

第七章:对象群体的组织
对象数组
查找
删除
排序
二维数组
集合
各种常见方法
向量
Enumeration
Iterable
map
hash

第八章:多线程
test1 thread
runable接口 继承和共享问题
runnable 共享 同个对象
runnable 共享 p256
后台线程 守护进程
线程的生命周期
线程的优先级 setpriority

第七章:对象群体的组织

package seventh;

import java.io.Serializable;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;

//对象群体的组织

public class test {
	public static <E, T> void main(String[] args){
		
		//对象数组
		
		
		//
		Book xbook[];
		library xLibrary=new library("龙湖",2); //注意数组大小 这里设置最大8
		xbook=new Book[xLibrary.getSize()];
		for(int i=0;i<xLibrary.getSize();i++) {
			//System.out.println("asa:"+getBook().getName());
			xbook[i]=getBook();
			System.out.println("xbook: "+xbook[i].getName());
		}
		
		//
		xLibrary.setBook(xbook);
		//System.out.print(xLibrary);
		String ssString=xLibrary.toString();
		//toString 方法在这里重载后没有再定义
		System.out.println(ssString);
		
		
		//查找
		int find_test=xLibrary.find("xiaoming");
		System.out.println(find_test);
		//增加
		xLibrary.add("xiaohong",321);
		
		//删除
		
		//排序
		
		//二维数组
		
		//集合
		
		//各种常见方法
		
		//向量
		Vector<String>tVector=new Vector<String>();
		tVector.add("aa");
		tVector.add("b");
		System.out.println(tVector.get(1));
		System.out.println(tVector);
		
		//Enumeration
		Enumeration<E>enumeration=(Enumeration<E>) tVector.elements();
		while (enumeration.hasMoreElements()) {
			E e = (E) enumeration.nextElement();
			System.out.println(e);
		}
		
		//Iterable
		Iterator<String>nums=tVector.iterator();
		while (nums.hasNext()) {
			System.out.println(nums.next());
		}
		
		//map
		
		//hash
		
		//
		
		
	}
	
	public static Book getBook() {
		Book yBook = new Book(null,0);
		
		//文件
		
		//手动输入
		
		//测试
		yBook.setName("xiaoming");
		yBook.setPrice(123);
		System.out.print("ybook: "+yBook.getName()+"\n");
		System.out.print(yBook.getPrice()+"\n");
		return yBook;
	}
	
	
}


//Book类代码代码来自:https://www.cnblogs.com/xhnxhnu/p/9124534.html
class Book implements Serializable{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String name;
    private int price;
    public Book(String n ,int string) {
        name = n;
        price = string;
    }
    public void getInfo1() {
		// TODO Auto-generated method stub
		
	}
	public Book(Book book) {
		// TODO Auto-generated constructor stub
	}
	public String getName() {
		return name;
	}
	public int getPrice() {
		return price;
	}
	public void setName(String n) {
        name = n;
    }
    public void setPrice(double p) {
        price = (int) p;
    }
    public String getInfo() {
        return "书名"+name+"\n"+
                "单价"+price;
    } 
}

//library
class library {
	
	private String name;
	private int size;
	private Book book[];
	static int cap=8;
	
	//构造方法
	public library(String name,int size) {
		// TODO Auto-generated constructor stub
		this.name=name;
		this.size=size;
		book=new Book[cap];
	}
	
	public void add(String string, int i) {
		// TODO Auto-generated method stub
		
	}

	//get name
	public String getName() {
		return name;
	}
	//get cap
	public static int getCap() {
		return cap;
	}
	//
	public Book[] getBook() {
		return book;
	}
	public int getSize() {
		return size;
	}
	public void setName(String name) {
		this.name = name;
	}
	public static void setCap(int cap) {
		library.cap = cap;
	}
	public void setSize(int size) {
		if (size>cap) {
			System.out.println("size超了");
			return;
		}
		this.size = size;
	}
	
	//
	public void setBook(Book...book) {
		for(int i=0;i<size;i++) {
			System.out.println("test: "+book[i].getName()+" "+book[i].getPrice());
			this.book[i]=book[i];
			System.out.println("book: "+this.book[i].getName());
		}
		this.size = book.length;
		System.out.println(size);
	}
	
	
	
	//尝试输出方法
    public void testPrintln() {
        Book arr[] = new Book[3];//开辟数组 空间
        arr[0] = new Book("java",10);//对象需要分别实例化
        arr[1] = new Book("js",20);
        arr[2] = new Book("py",30);
        for(int i=0; i<arr.length; i++) {
            System.out.println(arr[i]);
            System.out.println(arr[i].getInfo());
        }
        
//        for(int i=0;i<arr.length;i++) {
//        	if(arr[i].getInfo()!=null) {
//        		System.out.println(arr[i].getInfo());
//        	}
//        }
        
    }
    
    //重写toString
    @Override
    public String toString() {
    	String s;
    	s=this.book[0].getName();
    	System.out.println("toString:"+this.book[0].getName());
		return s;	
    }
    
    //查找信息
    public int find(String id){
    	for(int i = 0;i<size;i++) {
    		if(book[i].getName().equals(id)) {
    			return i;
    		}
    	}
		return -1;
    }
    
    //增加信息
    public boolean add(Book aBook) {
    	if(size==cap) {
    		return false;
    	}
    	//=-1  是错的
		if(this.find(aBook.getName())>=-1){
			return false;
		}
		
		String name=aBook.getName();
		int price=aBook.getPrice();
		this.book[size]=new Book(name,price);
		size++;
    	return true;
    	
	}
    
    
    
    
    
}

第八章:多线程

package eighth;


//多线程


public class test {
	public static void main(String[] args) {
		
		//test1 thread
		TestThread thread1=new TestThread("thread1");
		TestThread thread2=new TestThread("thread2");
		TestThread thread3=new TestThread("thread3");
		System.out.println("start: ");
		thread1.start();
		thread2.start();
		thread3.start();
		System.out.print("asas"); 
		
		//runable接口 继承和共享问题
		 
		//runnable 共享 同个对象
		TestRunnable testRunnable=new TestRunnable();
		System.out.println("runnable start:");
		new Thread(testRunnable,"Thread1").start();
		new Thread(testRunnable,"Thread2").start();
		new Thread(testRunnable,"Thread3").start();
		System.out.println("finished");
		
		
		//runnable 共享  p256
		Tickets tickets=new Tickets(10);
		new Producer(tickets).start();
		new Consumer(tickets).start();
		
		
		//后台线程 守护进程
		
		//线程的生命周期
		
		//线程的优先级
		//setpriority
		
		
		
	}
}

class TestThread extends Thread{
	private int sleepTime;
	public TestThread(String name) {
		// TODO Auto-generated constructor stub
		super(name);
		sleepTime=(int)(Math.random()*6000);
	}
	@Override
	public void run() {
		try {
			System.out.println(getName()+":"+sleepTime);
			Thread.sleep(sleepTime);
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(getName()+" finished");
		}
	}
}



class TestRunnable implements Runnable{
	private int sleepTime;
	public TestRunnable() {
		// TODO Auto-generated constructor stub
		sleepTime=(int)(Math.random()*6000);
	}
	public void run() {
		try {
			System.out.println(Thread.currentThread().getName()+"sleep: "+sleepTime);
			Thread.sleep(sleepTime);		
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(Thread.currentThread().getName()+"finished");
		}
	}
}


//存一张,取一张
class Tickets{
	int size;
	int number=0;
	int i=0;
	boolean available=false;
	public Tickets(int size) {
		// TODO Auto-generated constructor stub
		this.size=size;
	}
	public synchronized void put() {
		if(available) {
			try {
				wait();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		System.out.println("put:"+(++number));
		available=true;
		notify();
	}
	public synchronized void sell() {
		if(!available) {
			try {
				wait();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		System.out.println("buys : "+(number));
		available=false;
		notify();
		if(number==size) {
			number=size+1;
		}
	}
}

class Producer extends Thread{
	Tickets tickets=null;
	public Producer(Tickets tickets) {
		// TODO Auto-generated constructor stub
		this.tickets=tickets;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(tickets.number<tickets.size) {
			tickets.put();
		}
	}
	
}

class Consumer extends Thread{
	Tickets tickets=null;
	public Consumer(Tickets tickets) {
		// TODO Auto-generated constructor stub
		this.tickets=tickets;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(tickets.i<tickets.size) {
			tickets.sell();
		}
	}
	
}


//存与取一起
//class Tickets{
//	int size;
//	int number=0;
//	int i=0;
//	boolean available=false;
//	public Tickets(int size) {
//		// TODO Auto-generated constructor stub
//		this.size=size;
//	}
//	public synchronized void put() {
//		System.out.println("put:"+(++number));
//		available=true;
//	}
//	public synchronized void sell() {
//		if(available==true && i<number) {
//			System.out.println("sell"+(++i));
//		}
//		if(i==number) {
//			available=false;
//		}
//	}
//}
//
//class Producer extends Thread{
//	Tickets tickets=null;
//	public Producer(Tickets tickets) {
//		// TODO Auto-generated constructor stub
//		this.tickets=tickets;
//	}
//	@Override
//	public void run() {
//		// TODO Auto-generated method stub
//		while(tickets.number<tickets.size) {
//			tickets.put();
//		}
//	}
//	
//}
//
//class Consumer extends Thread{
//	Tickets tickets=null;
//	public Consumer(Tickets tickets) {
//		// TODO Auto-generated constructor stub
//		this.tickets=tickets;
//	}
//	@Override
//	public void run() {
//		// TODO Auto-generated method stub
//		while(tickets.i<tickets.size) {
//			tickets.sell();
//		}
//	}
//	
//}





2019.9.7

大学课程-Java-9-10章书籍正文代码编写

第九章:图形用户界面
API应用程序接口
Applet
Graphics
swing
JFC
AWT

第十章:JDBC与数据库访问

第九章:图形用户界面

package ninth;

import java.applet.Applet;

//图形用户界面

public class test {
	public static void main(String[] args) {
		
		//API应用程序接口
		
		//Applet
		
		//Graphics
		
		//swing
		
		//JFC
		
		//AWT
		
		//
		
		
		
		
	}
	
	
}

第十章:JDBC与数据库访问

package tenth;

//JDBC与数据库访问
import java.sql.*;

public class test {
	public static void main(String[] args) throws Exception{
		
		//https://www.runoob.com/java/java-mysql-connect.html
		//String DBDriver="sun.jdbc.odbc.JdbcOdbcDriver";
		//String DBDriver="com.mysql.cj.jdbc.Driver";
		String DBDriver="com.mysql.jdbc.Driver";
		//String conectionStr="jdbc:odbc:test"; //test数据库
		String conectionStr="jdbc:mysql://localhost:3306/test";
		Connection connection=null;
		Statement statement=null;
		ResultSet rSet=null;
		Class.forName(DBDriver);			//加载驱动器
		connection=DriverManager.getConnection(conectionStr,"root","root123");
		statement=connection.createStatement(); //创建statement对象
		
		//查询
		rSet=statement.executeQuery("select * from users");
		while(rSet.next()) {
			System.out.println(rSet.getInt("id"));
			System.out.println(rSet.getString("password"));
		}
		
		//添加
		statement.executeUpdate("insert into user values(2,'admin','admin123')");
		
		//删除
		
		//关闭连接
		statement.close();
		connection.close();
	}

}

2019.9.7

大学课程-Java-11-12章书籍正文代码编写

书上的代码也不多 也就是Hello World吧,主要的第一次要把环境运行起来

本篇也只写了hello world并运行

一.servlet
创建servlet项目
创建包
运行

二.jsp

一.servlet

1.创建servlet项目
new->project->Dynamic web project
命令为test_servlet

2.在src目录下创建包eleventh,再新建class,命名为HelloWorld
代码:(https://www.runoob.com/servlet/servlet-first-example.html)

package eleventh;

//https://blog.csdn.net/s896500398/article/details/52864458
//https://www.runoob.com/servlet/servlet-first-example.html
//导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

//扩展 HttpServlet 类
public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException
{
   // 执行必需的初始化
   message = "Hello World";
}

public void doGet(HttpServletRequest request,
                 HttpServletResponse response)
         throws ServletException, IOException
{
   // 设置响应内容类型
   response.setContentType("text/html");

   // 实际的逻辑是在这里
   PrintWriter out = response.getWriter();
   out.println("<h1>" + message + "</h1>");
}

public void destroy()
{
   // 什么也不做
}
}

4.运行
右键HelloWorld.java run as server(个人这里在eclipse里直接404,换了url路径映射的方法)
在web.xml添加:(https://blog.csdn.net/s896500398/article/details/52864458)

<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>eleventh.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

5.

这时直接右键run as或者输入test_servlet/hello都可以访问到

二.jsp

jsp代码直接在webcontent目录创建first.jsp
右键run as server即可看到

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>asdas</h1>
</body>
</html>

2019.9.10

发表评论

电子邮件地址不会被公开。 必填项已用*标注