java基础知识大全

 
 Java快速上手
 JVM内存结构及其调优
  在Eclipse下开发Java程序
  在Linux下开发Java
   Java核心语法详解
  Java面向对象编程
  Java面向对象编程扩展
  Java编码规范与样式
 
  Java输入/输出流


  Java多线程编程

实现runnable接口:
package test;
import java.util.Date;
public class TestRunnable implements Runnable {
public int time;// 休眠时间
public String user;// 调用用户
// 构造函数
public TestRunnable(int time, String user) {
this.time = time;
this.user = user;
}
// 线程体
public void run() {
while (true) {
try {
System.out.println(user + "休息" + time + "ms - " + new Date());
Thread.sleep(time);
} catch (Exception e) {
System.out.println(e);
}
}
}
// 启动线程实例
public static void main(String args[]) {
TestRunnable thread1 = new TestRunnable(1000, "Jack");
new Thread(thread1).start();
TestRunnable thread2 = new TestRunnable(3000, "Mike");
new Thread(thread2).start();
}
}

继承Thread类
package test;
import java.util.Date;
public class TestThread extends Thread {
public int time;// 休眠时间
public String user;// 调用用户
// 构造函数
public TestThread(int time, String user) {
this.time = time;
this.user = user;
}
// 线程体
public void run() {
while (true) {
try {
System.out.println(user + "休息" + time + "ms - " + new Date());
Thread.sleep(time);
} catch (Exception e) {
System.out.println(e);
}
}
}
// 启动线程实例
public static void main(String args[]) {
TestThread thread1 = new TestThread(1000, "Jack");
//TestThread thread2 = new TestThread(3000, "Mike");
thread1.setPriority(1);
//thread2.setPriority(Thread.MAX_PRIORITY);
thread1.start();
//thread2.start();
}
}

TreadGroup
package test;
public class TestThreadGroup {
public static void main(String args[]) {
ThreadGroup group1=new ThreadGroup("group1");
ThreadGroup group2=new ThreadGroup(group1,"group2");
Thread t1 = new Thread(group1, new TestThread(1000, "AAA"));
Thread t2 = new Thread(group2, new TestThread(1000, "BBB"));
Thread t3 = new Thread(group2, new TestThread(1000, "CCC"));
t1.start();
t2.start();
t3.start();
System.out.println(group1.activeCount());
System.out.println(group2.activeCount());
System.out.println(group1.activeGroupCount());
}
}

线程池:

TimerTask:

package test;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TestTimerTask extends TimerTask {
public void run() {
System.out.println(new Date());
}

public static void main(String[] args) {
Timer timer = new Timer();
TimerTask task = new TestTimerTask();
timer.schedule(task, 1000, 1000);
}
}

线程同步:

package test;
public class CheckInOut {
public static void main(String[] args) {
BankCard card = new BankCard();
Parent px = new Parent(card, "爸爸", 1500, 500);
Parent py = new Parent(card, "妈妈", 1000, 800);
Parent pz = new Parent(card, "爷爷", 800, 1000);
Children ca = new Children(card, "大女儿", 400, 600);
Children cb = new Children(card, "二女儿", 300, 600);
Children cc = new Children(card, "三儿子", 500, 600);
new Thread(px).start();
new Thread(py).start();
new Thread(pz).start();
new Thread(ca).start();
new Thread(cb).start();
new Thread(cc).start();
}
}
class BankCard {
int sum = 0;
// 存款
public synchronized void save(String name, int count) {
// 如果存了足够的钱就不在存了
while (sum > 5000) {
try {
System.out.println(name + "\t存款: 发现钱够了");
// 等待,并且从这里退出push()
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 注意,notifyAll()以后,并没有退出,而是继续执行直到完成。
this.sum += count;
System.out.println(name + "\t存入了 [¥" + count + "]\t余额 [¥" + this.sum + "]");

// 因为我们不确定有没有线程在wait(),所以我们既然存了钱,就唤醒有可能等待的孩子,让他们醒来,准备取款
notifyAll();
System.out.println("\t" + name + "告诉孩子存钱了");
}

// 取款
public synchronized void cost(String name, int count) {
// 如果钱不够了,就不再取款
while (sum < count) {
try {
System.out.println(name + "\t取款: 等钱花" + count);
// 等待,并且从这里退出pop()
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

// 注意,notifyAll()以后,并没有退出,而是继续执行直到完成。
this.sum -= count;
System.out.println(name + "\t取走了 [¥" + count + "]\t余额 [¥" + this.sum + "]");

// 因为我们不确定有没有线程在wait(),所以我们既然消费了产品,就唤醒有可能等待的生产者,让他们醒来,准备生产
notifyAll();
System.out.println("\t" + name + "告诉父母取钱了");
}
}
class Parent implements Runnable {
BankCard card = null;// 银行卡
String name;// 姓名
int count;// 存款数量
int interval;// 存款时间间隔
Parent(BankCard card, String name, int count, int interval) {
this.card = card;
this.name = name;
this.count = count;
this.interval = interval;
}
public void run() {
while (true) {
card.save(name, count);
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Children implements Runnable {
BankCard card = null;// 银行卡
String name;// 姓名
int count;// 取款数量
int interval;// 取款时间间隔
Children(BankCard card, String name, int count, int interval) {
this.card = card;
this.name = name;
this.count = count;
this.interval = interval;
}
public void run() {
while (true) {
//int count = (int) (Math.random() * degree);
card.cost(name, count);
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

生产者消费者模型:

package test;
public class ProducerConsumer {
public static void main(String[] args) {
ProductList ps = new ProductList();
Producer px = new Producer(ps, "生产者X");
Producer py = new Producer(ps, "生产者Y");
Consumer ca = new Consumer(ps, "消费者A");
Consumer cb = new Consumer(ps, "消费者B");
Consumer cc = new Consumer(ps, "消费者C");
new Thread(px).start();
new Thread(py).start();
new Thread(ca).start();
new Thread(cb).start();
new Thread(cc).start();
}
}


/**
* @author liuzhongbing
* 产品类
*/
class Product {
private String producedBy = "N/A";
private String consumedBy = "N/A";


// 构造函数,指明及生产者名字
Product(String producedBy) {
this.producedBy = producedBy;
}

// 消费,需要指明消费者名字
public void consume(String consumedBy) {
this.consumedBy = consumedBy;
}


public String toString() {
return "产品, 生产者 = " + producedBy + ", 消费者 = "
+ consumedBy;
}

public String getProducedBy() {
return producedBy;
}


public void setProducedBy(String producedBy) {
this.producedBy = producedBy;
}

public String getConsumedBy() {
return consumedBy;
}


public void setConsumedBy(String consumedBy) {
this.consumedBy = consumedBy;
}
}

/**
* @author liuzhongbing
* 这个class就是仓库,是生产者跟消费者共同争夺控制权的同步资源
*/
class ProductList {
int index = 0;
Product[] productList = new Product[6];


// push使用来让生产者放置产品的
public synchronized void push(Product product) {
// 如果仓库满了
while (index == productList.length) {
try {
System.out.println("  " + product.getProducedBy() + " is waiting.");
// 等待,并且从这里退出push()
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 注意,notifyAll()以后,并没有退出,而是继续执行直到完成。
productList[index] = product;
index++;
System.out.println(index + " " + product.getProducedBy() + " 生产了: " + product);

// 因为我们不确定有没有线程在wait(),所以我们既然生产了产品,就唤醒有可能等待的消费者,让他们醒来,准备消费
notifyAll();
System.out.println("  " + product.getProducedBy() + " sent a notifyAll().");
}


// pop用来让消费者取出产品的
public synchronized Product pop(String consumerName) {
// 如果仓库空了
while (index == 0) {
try {
System.out.println("  " + consumerName + " is waiting.");
// 等待,并且从这里退出pop()
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

// 注意,notifyAll()以后,并没有退出,而是继续执行直到完成。
// 取出产品
index--;
Product product = productList[index];
product.consume(consumerName);
System.out.println(index + " " + product.getConsumedBy() + " 消费了: " + product);

// 因为我们不确定有没有线程在wait(),所以我们既然消费了产品,就唤醒有可能等待的生产者,让他们醒来,准备生产
notifyAll();
System.out.println("  " + consumerName + " sent a notifyAll().");
return product;
}
}


/**
* @author liuzhongbing
* 生产者
*/
class Producer implements Runnable {


String name;
ProductList ps = null;


Producer(ProductList ps, String name) {
this.ps = ps;
this.name = name;
}


public void run() {
while (true) {
Product product = new Product(name);
ps.push(product);
try {
Thread.sleep((int) (Math.random() * 300));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}


class Consumer implements Runnable {


String name;
ProductList ps = null;


Consumer(ProductList ps, String name) {
this.ps = ps;
this.name = name;
}


public void run() {
while (true) {
ps.pop(name);
try {
Thread.sleep((int) (Math.random() * 600));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

Java常用实体类:

String相关类:

package test.String;
public class TestString {

static int count = 100;// 循环次数

// 测试String
public static void testString() {
long start = System.nanoTime();
String str = "";
for (int i = 0; i < count; i++) {
str += "," + i;
}
long end = System.nanoTime();
System.out.println("String:" + (end - start));
}


// 测试StringBuffer
public static void testStringBuffer() {
long start = System.nanoTime();
StringBuffer str = new StringBuffer();
for (int i = 0; i < count; i++) {
str.append(",").append(i);
}
long end = System.nanoTime();
System.out.println("StringBuffer:" + (end - start));
}


// 测试StringBuilder
public static void testStringBuilder() {
long start = System.nanoTime();
StringBuilder str = new StringBuilder();
for (int i = 0; i < count; i++) {
str.append(",").append(i);
}
long end = System.nanoTime();
System.out.println("StringBuilder:" + (end - start));
}


public static void main(String[] args) {
//TestString.testString();
TestString.testStringBuffer();
TestString.testStringBuilder();
}
}


日期实体类:

package test.Date;
import java.util.Date;
public class TestDate {
public static void main(String[] args) {
long cur = System.currentTimeMillis();
Date date = new Date(cur);
System.out.println(date);//Thu Mar 26 17:34:54 CST 2015
}
}

package test.Date;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDateFormat {
public static void main(String[] args) throws Exception {
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(format.format(date));

String str = "2008-08-08 08:08:08";
System.out.println(format.parse(str));
}
}

//2015-03-26 17:36:03
//Fri Aug 08 08:08:08 CST 2008


系统实体类:

数组拷贝:

package test.System;
public class TestSystemArrayCopy {
public static void main(String args[]) {
// 定义源数组
int[] a = new int[10];
for (int i = 0; i < 10; i++) {
a[i] = i+1;
}

// 拷贝目标数组
int[] b = new int[5];
System.arraycopy(a, 2, b, 1, 4);

// 输出目标数组
for (int i = 0; i < 5; i++) {
System.out.println("b" + i + "=" + b[i]);
}
}
}

系统环境变量获取

package test.System;
import java.util.Iterator;
import java.util.Map;
public class TestSystemEnv {
public static void main(String args[]) {

// 取得环境变量列表
Map<String, String> map = System.getenv();
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
String key = it.next();// 键
String value = map.get(key);// 值
System.out.println(key + "=" + value);
}

// 取得某一个环境变量
String javahome = System.getenv("JAVA_HOME");// 取得JAVA_HOME
String path = System.getenv("PATH");// 取得PATH
String classpath = System.getenv("CLASSPATH");// 取得CLASSPATH
System.out.println("javahome=" + javahome);
System.out.println("path=" + path);
System.out.println("classpath=" + classpath);
}
}

system 退出:

package test.System;
import java.util.Iterator;
import java.util.Map;
public class TestSystemEnv {
public static void main(String args[]) {

// 取得环境变量列表
Map<String, String> map = System.getenv();
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
String key = it.next();// 键
String value = map.get(key);// 值
System.out.println(key + "=" + value);
}

// 取得某一个环境变量
String javahome = System.getenv("JAVA_HOME");// 取得JAVA_HOME
String path = System.getenv("PATH");// 取得PATH
String classpath = System.getenv("CLASSPATH");// 取得CLASSPATH
System.out.println("javahome=" + javahome);
System.out.println("path=" + path);
System.out.println("classpath=" + classpath);
}
}

系统属性:

package test.System;

import java.util.Enumeration;
import java.util.Properties;
public class TestSystemProperty {
public static void main(String args[]) {
// 取得系统属性列表
Properties properties = System.getProperties();
Enumeration<Object> e = properties.keys();
while (e.hasMoreElements()) {
String key = (String)e.nextElement();// 键
String value = properties.getProperty(key);// 值
System.out.println(key + "=" + value);
}

// 取得某一个系统属性
String osname = System.getProperty("os.name");// 取得os.name
String osversion = System.getProperty("os.version");// 取得os.version
String javaname = System.getProperty("java.vm.name");// 取得java.vm.name
String javaversion = System.getProperty("java.version");// 取得java.version
System.out.println("操作系统名称=" + osname);
System.out.println("操作系统版本=" + osversion);
System.out.println("JVM名称=" + javaname);
System.out.println("Java版本=" + javaversion);
System.setProperty("java.version2", "aa");
System.setProperty("java.version2", "aa");
String javaversion2 = System.getProperty("java.version2");
System.out.println("Java版本=" + javaversion2);
}
}

系统时间:

 package test.System;


public class TestSystemTime {
public static void main(String args[]) {
long startMillisTime = System.currentTimeMillis();
long startNanoTime = System.nanoTime();
System.out.println("startMillisTime=" + startMillisTime);
System.out.println("startNanoTime=" + startNanoTime);


// 定义源数组
int[] a = new int[10];
for (int i = 0; i < 10; i++) {
a[i] = i+1;
}

// 拷贝目标数组
int[] b = new int[5];
System.arraycopy(a, 2, b, 1, 4);

// 输出目标数组
for (int i = 0; i < 5; i++) {
System.out.println("b" + i + "=" + b[i]);
}


long endMillisTime = System.currentTimeMillis();
long endNanoTime = System.nanoTime();
System.out.println("endMillisTime=" + endMillisTime);
System.out.println("endNanoTime=" + endNanoTime);

System.out.println("毫秒:" + (endMillisTime - startMillisTime));
System.out.println("微秒:" + (endNanoTime - startNanoTime));
}
}


程序运行时:

package test.Runtime;
public class TestRuntimeMemory {
public static void main(String[] args) {
System.out.println("内存总量:" + Runtime.getRuntime().totalMemory());
System.out.println("最大内存量:" + Runtime.getRuntime().maxMemory());
System.out.println("空闲内存量:" + Runtime.getRuntime().freeMemory());
}
}
package test.Runtime;

public class TestRuntimeHook {
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
// 关闭线程
System.out.println("系统正在退出……");
}
});

while (true) {
String line =  System.console().readLine();
System.out.println(line);
if (line.equals("bye")) {
System.exit(0);
}
}
}
}

package test.Runtime;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;


public class TestRuntimeExec {
public static void main(String[] args) {
try {
// 打开记事本
Runtime.getRuntime().exec("notepad");
// 打开word
Runtime.getRuntime().exec("cmd /c start Winword");
// 执行批处理
Runtime.getRuntime().exec("cmd.exe /C start d:/demo/run.bat");
} catch (Exception e) {
e.printStackTrace();
}

try {
Process p = Runtime.getRuntime().exec("d:/demo/run.bat");
InputStream in = p.getInputStream();
String line = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
in.close();
p.waitFor();
} catch (InterruptedException e) {  
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}


Java常用集合类

Java正则表达式

Xml与属性文件


  Java图形编程
  Java GUI库对比
  AWT多媒体编程
  AWT多媒体编程
  Swing图形界面开发
  SWT图形界面开发
  SWT增强组件库JFace
 
  Applet组件编程
  Java网络编程
  DIO非阻塞编程
  RMI分布式网络编程
  CORBA分布式网络编程
  Java反射编程与动态代理

java反射编程:

package org.amigo.reflection;
import java.awt.Button;
import java.lang.reflect.Method;
import java.util.Hashtable;
public class ReflectionTest {
public ReflectionTest() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
ReflectionTest reflectionTest = new ReflectionTest();
reflectionTest.getNameTest();
reflectionTest.getMethodTest();
}
public void getNameTest() throws Exception{
System.out.println("===========begin getNameTest============");
//通过String对象获取,String类的类名
String name = "dflajdf";
Class cls = name.getClass();
System.out.println("String类名:"+ cls.getName());
//通过Button对象获取button的类名
Button btn = new Button();
Class btnclass = btn.getClass();
System.out.println("btnclass类名:"+ btnclass.getName());
//通过button对象获取button父类的名字
Class btnSuperClass = btnclass.getSuperclass();
System.out.println("btnSuperClass类名:"+ btnSuperClass.getSimpleName() );

Class clsTest = Class.forName("java.awt.Button");
System.out.println("clsTest name: " + clsTest.getName());
System.out.println("===========end getNameTest============");
}
public void getMethodTest() throws Exception{
System.out.println("===========begin getMethodTest==========");
//通过名字获取类对象
Class cls = Class.forName("org.amigo.reflection.ReflectionTest");
//定义类数组
Class ptypes[] = new Class[2];
ptypes[0] = Class.forName("java.lang.String");
ptypes[1] = Class.forName("java.util.Hashtable");
//通过方法名和方法参数获取类的方法
Method method =cls.getMethod("testMethod", ptypes);
Object args[] = new Object[2];
//对参数赋值
args[0] = "hello,my dear!";
Hashtable<String,String> ht =new Hashtable<String,String>();
ht.put("name", "hhhhh");
args[1] = ht;
 
String returnStr = (String) method.invoke(new ReflectionTest(), args);
System.out.println("returnStr= " + returnStr);
    System.out.println("===========end getMethodTest==========");
}
public String testMethod(String str, Hashtable ht) throws Exception {
        String returnStr = "返回值";
        System.out.println("测试testMethod()方法调用");
        System.out.println("str= " + str);
        System.out.println("名字= " + (String) ht.get("name"));
        System.out.println("结束testMethod()方法调用");
        return returnStr;
}
}

java动态代理:

  Java泛型编程
  Java注释符编程
 Java 5.0 语言新特性

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值