Java_基础知识回顾
2015-02-03 11:27
525 查看
1、ByteArrayInputStream、 ByteArrayOutputStream
String str = "ZHANGSAN";
//System.out.println(str.toLowerCase());
ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int b;
while((b = inputStream.read()) != -1){
char lowerCase = Character.toLowerCase((char)b);
outputStream.write(lowerCase);
}
byte[] lowerCases = outputStream.toByteArray();
System.out.println(new String(lowerCases,0, lowerCases.length));
全部在内存中完成byte的转换
2、PrintStream:向目标打印
属于OutputStream的实现类,向目标(可能是文件、标准输出屏幕、输出流、网络等)打印各种样式,不过比一般的输出提供了更多的打印方式,可以打印各种数据类型和样式等
OutputStream outputStream = System.out;
outputStream.write("helloABC张三".getBytes());
outputStream.close();
列出当前操作系统的系统参数,输出到文件中
PrintStream printStream = new PrintStream("hello.txt");
System.getProperties().list(printStream);
printStream.close();
3、InputStreamReader、OutputStreamWriter, 计算机存储都是字节流的形式,而读取到内存中需要识别一个个的字符(人只能识别字符),有可能1个字节就代表一个字符(例如英文),也有可能多个字节才能转换成一个字符(例如中文),如果中间存在丢失或无法转换,则看到的就是一堆?
InputStreamReader:将输入的内容字节变成字符
OutputStreamWriter:将输出的内容从字符变成字节
4、合并流:SequenceInputStream
File file1 = new File("hello.txt");
File file2 = new File("test.txt");
InputStream inputStream1 = new FileInputStream(file1);
InputStream inputStream2 = new FileInputStream(file2);
SequenceInputStream sequenceInputStream = new SequenceInputStream(inputStream1,
inputStream2);
BufferedInputStream bufferedInputStream = new BufferedInputStream(sequenceInputStream);
int c;
while((c = bufferedInputStream.read()) != -1){
System.out.print((char)c);
}
bufferedInputStream.close();
sequenceInputStream.close();
inputStream1.close();
inputStream2.close();
测试结果:helloworld
在实验中,从bufferedInputStream去取到两个文件大小相加的byte数组中,代码如下,转换出来有问题,有点奇怪,只读到了前一个流中的内容,后面一个流中的内容没读取进来。思考中...
File file1 = new File("hello.txt");
File file2 = new File("test.txt");
InputStream inputStream1 = new FileInputStream(file1);
InputStream inputStream2 = new FileInputStream(file2);
SequenceInputStream sequenceInputStream = new SequenceInputStream(inputStream1,
inputStream2);
BufferedInputStream bufferedInputStream = new BufferedInputStream(sequenceInputStream);
int length = (int) (file1.length() + file2.length());
byte[] b = new byte[length];
bufferedInputStream.read(b, 0, length);
System.out.println(new String(b,0,length));
bufferedInputStream.close();
sequenceInputStream.close();
inputStream1.close();
inputStream2.close();
测试结果如下:hello
5、Zip压缩与解压
压缩程序:
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream("hello.zip"));
zipOutputStream.setLevel(9);
ZipEntry zipEntry = new ZipEntry("a.txt");
zipOutputStream.putNextEntry(zipEntry);
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("test.txt"));
int content;
while((content = bufferedInputStream.read()) != -1){
zipOutputStream.write(content);
}
bufferedInputStream.close();
zipOutputStream.closeEntry();
zipOutputStream.flush();
zipOutputStream.close();
解压程序:
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream("hello.zip"));
ZipEntry zipEntry = null;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
new FileOutputStream(zipEntry.getName()));
int content = 0;
while((content = zipInputStream.read()) != -1){
bufferedOutputStream.write(content);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
zipInputStream.close();
6、zip压缩某目录下的所有文件及子文件
public void zipDirectory(File pathname, ZipOutputStream zipOutputStream) throws Exception {
if (!pathname.isDirectory()) {
return;
}
File[] files = pathname.listFiles();
for (File file : files) {
if (file.isDirectory()) {
zipDirectory(file, zipOutputStream);
} else {
ZipEntry zipEntry = new ZipEntry(pathname.getName() + File.separator
+ file.getName());
zipOutputStream.putNextEntry(zipEntry);
BufferedInputStream bufferedInputStream = new BufferedInputStream(
new FileInputStream(file));
int i;
while ((i = bufferedInputStream.read()) != -1) {
zipOutputStream.write(i);
}
bufferedInputStream.close();
zipOutputStream.flush();
zipOutputStream.closeEntry();
}
}
}
问题:中文编码存在问题,建议选用import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream,由于其存在方法out.setEncoding("gbk");//指定编码为gbk
6、ThreadLocal
final ThreadLocal<String> threadLocal = new ThreadLocal<String>();
threadLocal.set("main--");
Thread thread = new Thread() {
@Override
public void run() {
threadLocal.set("thread--");
Thread.yield();
System.out.println(Thread.currentThread().getName() + ":" + threadLocal.get());
}
};
thread.start();
Thread.yield();
System.out.println(Thread.currentThread().getName() + ":" + threadLocal.get());
7、数组和List之间的转换
数组->List: Arrays.asList(a)
List->数组:list.toArray()
8、正则表达式
(1)^:在[]内表示取反,在外面表示开头
(2)group
String regex = "[a-z]{3,5}";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("Abc_defgh_aa_ABCD1");
while (matcher.find()) {
System.out.print("位置[左闭右开区间):"+matcher.start() + "_" + matcher.end() + ", 匹配内容:");
System.out.println(matcher.group());
}
测试结果:
位置[左闭右开区间):0_3, 匹配内容:Abc
位置[左闭右开区间):4_9, 匹配内容:defgh
位置[左闭右开区间):13_17, 匹配内容:ABCD
(3)邮件的正则表达式
[\\w[_.]]+@[\\w[_.]]+\\.[\\w]+
(4)"."点号在正则表达式中表示任何字符, 需要表示点号的时候必须转义\\.
(5)group的分组
分组是以正则表达式中的小括号'()'为标准的,当匹配成功后,group或group(0)表示匹配的整个字符串,group(1)代表正则中第一个小括号匹配到的内容,group(2)代表第二个小括号代表的内容,依次类推
(6)匹配require引入文件
"^[\\s]*#require[\\s]*\\(\"([\\w./]+)\"\\)[\\s]*$"含义为:以任意空白字符开头,在#require,再任意空白字符,再(",再任意字母、点号、斜线, 再"),最后任意个空白字符结尾
测试代码:
public static void main(String[] args) {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(new File(
"C:/Documents and Settings/***/My Documents/tmp/hello.js"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,
Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = "";
try {
while ((line = bufferedReader.readLine()) != null) {
String requireFile = getRequireFile(line);
System.out.println(requireFile);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
inputStreamReader.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static String getRequireFile(String line) {
String requireFile = "";
Pattern pattern = Pattern
.compile("^[\\s]*#require[\\s]*\\(\"([\\w./]+)\"\\)[\\s]*$", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
requireFile = matcher.group(1);
}
return requireFile;
}
测试文件内容:
var param;
#require("hello/world_util/alibaba123_utils.js")
#require("/abc/world_util/alibaba12666_utils.js")
测试结果
hello/world_util/alibaba123_utils.js
/abc/world_util/alibaba12666_utils.js
9、FileReader有待完备的地方,只能使用系统默认的字符集,而没有提供传递字符集的构造函数
FileReader继承了InputStreamReader,但并没有实现父类中带字符集参数的构造函数,所以
FileReader只能按系统默认的字符集来解码
10、阻塞队列:BlockingQueue
生产者中的 put() 操作会在没有空间可用时阻塞,而消费者的 take() 操作会在队列中没有任何东西时阻塞。
11、信号量:Semaphore, 允许规定数量的线程进入操作,释放之后其他进入执行
Runnable limitedCall = new Runnable() {
final Random rand = new Random();
final Semaphore available = new Semaphore(3);
int count = 0;
public void run() {
int time = rand.nextInt(15);
int num = count++;
try {
available.acquire();
System.out.println("Executing " + "long-running action for " + time
+ " seconds... #" + num);
Thread.sleep(time * 1000);
System.out.println("Done with #" + num + "!");
available.release();
} catch (InterruptedException intEx) {
intEx.printStackTrace();
}
}
};
for (int i = 0; i < 10; i++)
new Thread(limitedCall).start();
12、死锁
public class Demo06 {
public static void main(String[] args) {
DeadLock deadLock1 = new DeadLock();
DeadLock deadLock2 = new DeadLock();
deadLock1.setFlag(true);
deadLock2.setFlag(false);
new Thread(deadLock1).start();
new Thread(deadLock2).start();
}
}
class DeadLock implements Runnable {
private boolean flag = false;
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
private static Object object1 = new Object();
private static Object object2 = new Object();
public void run() {
if (flag) {
synchronized (object1) {
System.out.println(Thread.currentThread().getName() + " get object1.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object2) {
System.out.println(Thread.currentThread().getName() + " get object2.");
}
}
} else {
synchronized (object2) {
System.out.println(Thread.currentThread().getName() + " get object2.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object1) {
System.out.println(Thread.currentThread().getName() + " get object1.");
}
}
}
}
}
13、反射:通过classloader加载类,标准做法如下:
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) cl = MyClass.class.getClassLoader(); // fallback
Class clazz = cl.loadClass(name);
14、文件大小限制
错误做法:
public int getFileSize(File f) {
long l = f.length();
return (int) l;
}
正确做法如下:
不支持传递超过2GB的文件. 最好的做法是对长度进行检查, 溢出时抛出异常
public int getFileSize(File f) {
long l = f.length();
if (l > Integer.MAX_VALUE) throw new IllegalStateException("int overflow");
return (int) l;
}
15、线程sleep中断
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
or
while (true) {
if (Thread.currentThread().isInterrupted()) break;
}
16、开发中常用术语解释
java的几种对象(PO,VO,DAO,BO,POJO)解释
一、PO:persistant object 持久对象,可以看成是与数据库中的表相映射的java对象。最简单的PO就是对应数据库中某个表中的一条记录,多个记录可以用PO的集合。PO中应该不包含任何对数据库的操作。
二、VO:value object值对象。通常用于业务层之间的数据传递,和PO一样也是仅仅包含数据而已。但应是抽象出的业务对象,可以和表对应,也可以不,这根据业务的需要.个人觉得同DTO(数据传输对象),在web上传递。
三、DAO:data access object 数据访问对象,此对象用于访问数据库。通常和PO结合使用,DAO中包含了各种数据库的操作方法。通过它的方法,结合PO对数据库进行相关的操作。
四、BO:business object 业务对象,封装业务逻辑的java对象,通过调用DAO方法,结合PO,VO进行业务操作。
五、POJO:plain ordinary java object 简单无规则java对象,我个人觉得它和其他不是一个层面上的东西,VO和PO应该都属于它。
17、多线售票系统:
class TicketSeller implements Runnable {
private int ticketCount = 10;
@Override
public void run() {
while (ticketCount > 0) {
synchronized (this) {
if (ticketCount > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ " sell ticket: " + ticketCount--);
}
}
}
}
}
public class Demo01 {
public static void main(String[] args) {
TicketSeller ticketSeller = new TicketSeller();
new Thread(ticketSeller, "Thread A").start();
new Thread(ticketSeller, "Thread B").start();
new Thread(ticketSeller, "Thread C").start();
new Thread(ticketSeller, "Thread D").start();
}
}
测试结果:
Thread A sell ticket: 10
Thread A sell ticket: 9
Thread D sell ticket: 8
Thread D sell ticket: 7
Thread D sell ticket: 6
Thread C sell ticket: 5
Thread C sell ticket: 4
Thread C sell ticket: 3
Thread B sell ticket: 2
Thread B sell ticket: 1
18、中断处理
class TicketSeller implements Runnable {
@Override
public void run() {
try {
System.out.println("线程启动");
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("线程被中断");
// e.printStackTrace();
}
}
}
public class Demo01 {
public static void main(String[] args) throws InterruptedException {
TicketSeller ticketSeller = new TicketSeller();
Thread thread = new Thread(ticketSeller, "Thread A");
thread.start();
System.out.println("====主线程执行===");
Thread.sleep(1000);
// thread.interrupt();
System.out.println("线程被中断否:" + thread.isInterrupted());
thread.interrupt();
System.out.println("线程被中断否:" + thread.isInterrupted());
System.out.println("线程被中断否2:" + thread.isInterrupted());
System.out.println("主线程是否被中断:" + Thread.interrupted());
System.out.println("====主线程结束===");
}
}
测试结果:
====主线程执行===
线程启动
线程被中断否:false
线程被中断否:true
线程被中断否2:true
主线程是否被中断:false
线程被中断
====主线程结束===
结论:
interrupt中断该线程, isInterrupted检查该线程是否被中断, interrupted检查当前线程是否被中断。
String str = "ZHANGSAN";
//System.out.println(str.toLowerCase());
ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int b;
while((b = inputStream.read()) != -1){
char lowerCase = Character.toLowerCase((char)b);
outputStream.write(lowerCase);
}
byte[] lowerCases = outputStream.toByteArray();
System.out.println(new String(lowerCases,0, lowerCases.length));
全部在内存中完成byte的转换
2、PrintStream:向目标打印
属于OutputStream的实现类,向目标(可能是文件、标准输出屏幕、输出流、网络等)打印各种样式,不过比一般的输出提供了更多的打印方式,可以打印各种数据类型和样式等
OutputStream outputStream = System.out;
outputStream.write("helloABC张三".getBytes());
outputStream.close();
列出当前操作系统的系统参数,输出到文件中
PrintStream printStream = new PrintStream("hello.txt");
System.getProperties().list(printStream);
printStream.close();
3、InputStreamReader、OutputStreamWriter, 计算机存储都是字节流的形式,而读取到内存中需要识别一个个的字符(人只能识别字符),有可能1个字节就代表一个字符(例如英文),也有可能多个字节才能转换成一个字符(例如中文),如果中间存在丢失或无法转换,则看到的就是一堆?
InputStreamReader:将输入的内容字节变成字符
OutputStreamWriter:将输出的内容从字符变成字节
4、合并流:SequenceInputStream
File file1 = new File("hello.txt");
File file2 = new File("test.txt");
InputStream inputStream1 = new FileInputStream(file1);
InputStream inputStream2 = new FileInputStream(file2);
SequenceInputStream sequenceInputStream = new SequenceInputStream(inputStream1,
inputStream2);
BufferedInputStream bufferedInputStream = new BufferedInputStream(sequenceInputStream);
int c;
while((c = bufferedInputStream.read()) != -1){
System.out.print((char)c);
}
bufferedInputStream.close();
sequenceInputStream.close();
inputStream1.close();
inputStream2.close();
测试结果:helloworld
在实验中,从bufferedInputStream去取到两个文件大小相加的byte数组中,代码如下,转换出来有问题,有点奇怪,只读到了前一个流中的内容,后面一个流中的内容没读取进来。思考中...
File file1 = new File("hello.txt");
File file2 = new File("test.txt");
InputStream inputStream1 = new FileInputStream(file1);
InputStream inputStream2 = new FileInputStream(file2);
SequenceInputStream sequenceInputStream = new SequenceInputStream(inputStream1,
inputStream2);
BufferedInputStream bufferedInputStream = new BufferedInputStream(sequenceInputStream);
int length = (int) (file1.length() + file2.length());
byte[] b = new byte[length];
bufferedInputStream.read(b, 0, length);
System.out.println(new String(b,0,length));
bufferedInputStream.close();
sequenceInputStream.close();
inputStream1.close();
inputStream2.close();
测试结果如下:hello
5、Zip压缩与解压
压缩程序:
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream("hello.zip"));
zipOutputStream.setLevel(9);
ZipEntry zipEntry = new ZipEntry("a.txt");
zipOutputStream.putNextEntry(zipEntry);
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("test.txt"));
int content;
while((content = bufferedInputStream.read()) != -1){
zipOutputStream.write(content);
}
bufferedInputStream.close();
zipOutputStream.closeEntry();
zipOutputStream.flush();
zipOutputStream.close();
解压程序:
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream("hello.zip"));
ZipEntry zipEntry = null;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
new FileOutputStream(zipEntry.getName()));
int content = 0;
while((content = zipInputStream.read()) != -1){
bufferedOutputStream.write(content);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
zipInputStream.close();
6、zip压缩某目录下的所有文件及子文件
public void zipDirectory(File pathname, ZipOutputStream zipOutputStream) throws Exception {
if (!pathname.isDirectory()) {
return;
}
File[] files = pathname.listFiles();
for (File file : files) {
if (file.isDirectory()) {
zipDirectory(file, zipOutputStream);
} else {
ZipEntry zipEntry = new ZipEntry(pathname.getName() + File.separator
+ file.getName());
zipOutputStream.putNextEntry(zipEntry);
BufferedInputStream bufferedInputStream = new BufferedInputStream(
new FileInputStream(file));
int i;
while ((i = bufferedInputStream.read()) != -1) {
zipOutputStream.write(i);
}
bufferedInputStream.close();
zipOutputStream.flush();
zipOutputStream.closeEntry();
}
}
}
问题:中文编码存在问题,建议选用import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream,由于其存在方法out.setEncoding("gbk");//指定编码为gbk
6、ThreadLocal
final ThreadLocal<String> threadLocal = new ThreadLocal<String>();
threadLocal.set("main--");
Thread thread = new Thread() {
@Override
public void run() {
threadLocal.set("thread--");
Thread.yield();
System.out.println(Thread.currentThread().getName() + ":" + threadLocal.get());
}
};
thread.start();
Thread.yield();
System.out.println(Thread.currentThread().getName() + ":" + threadLocal.get());
7、数组和List之间的转换
数组->List: Arrays.asList(a)
List->数组:list.toArray()
8、正则表达式
(1)^:在[]内表示取反,在外面表示开头
(2)group
String regex = "[a-z]{3,5}";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("Abc_defgh_aa_ABCD1");
while (matcher.find()) {
System.out.print("位置[左闭右开区间):"+matcher.start() + "_" + matcher.end() + ", 匹配内容:");
System.out.println(matcher.group());
}
测试结果:
位置[左闭右开区间):0_3, 匹配内容:Abc
位置[左闭右开区间):4_9, 匹配内容:defgh
位置[左闭右开区间):13_17, 匹配内容:ABCD
(3)邮件的正则表达式
[\\w[_.]]+@[\\w[_.]]+\\.[\\w]+
(4)"."点号在正则表达式中表示任何字符, 需要表示点号的时候必须转义\\.
(5)group的分组
分组是以正则表达式中的小括号'()'为标准的,当匹配成功后,group或group(0)表示匹配的整个字符串,group(1)代表正则中第一个小括号匹配到的内容,group(2)代表第二个小括号代表的内容,依次类推
(6)匹配require引入文件
"^[\\s]*#require[\\s]*\\(\"([\\w./]+)\"\\)[\\s]*$"含义为:以任意空白字符开头,在#require,再任意空白字符,再(",再任意字母、点号、斜线, 再"),最后任意个空白字符结尾
测试代码:
public static void main(String[] args) {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(new File(
"C:/Documents and Settings/***/My Documents/tmp/hello.js"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,
Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = "";
try {
while ((line = bufferedReader.readLine()) != null) {
String requireFile = getRequireFile(line);
System.out.println(requireFile);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
inputStreamReader.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static String getRequireFile(String line) {
String requireFile = "";
Pattern pattern = Pattern
.compile("^[\\s]*#require[\\s]*\\(\"([\\w./]+)\"\\)[\\s]*$", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
requireFile = matcher.group(1);
}
return requireFile;
}
测试文件内容:
var param;
#require("hello/world_util/alibaba123_utils.js")
#require("/abc/world_util/alibaba12666_utils.js")
测试结果
hello/world_util/alibaba123_utils.js
/abc/world_util/alibaba12666_utils.js
9、FileReader有待完备的地方,只能使用系统默认的字符集,而没有提供传递字符集的构造函数
FileReader继承了InputStreamReader,但并没有实现父类中带字符集参数的构造函数,所以
FileReader只能按系统默认的字符集来解码
10、阻塞队列:BlockingQueue
生产者中的 put() 操作会在没有空间可用时阻塞,而消费者的 take() 操作会在队列中没有任何东西时阻塞。
11、信号量:Semaphore, 允许规定数量的线程进入操作,释放之后其他进入执行
Runnable limitedCall = new Runnable() {
final Random rand = new Random();
final Semaphore available = new Semaphore(3);
int count = 0;
public void run() {
int time = rand.nextInt(15);
int num = count++;
try {
available.acquire();
System.out.println("Executing " + "long-running action for " + time
+ " seconds... #" + num);
Thread.sleep(time * 1000);
System.out.println("Done with #" + num + "!");
available.release();
} catch (InterruptedException intEx) {
intEx.printStackTrace();
}
}
};
for (int i = 0; i < 10; i++)
new Thread(limitedCall).start();
12、死锁
public class Demo06 {
public static void main(String[] args) {
DeadLock deadLock1 = new DeadLock();
DeadLock deadLock2 = new DeadLock();
deadLock1.setFlag(true);
deadLock2.setFlag(false);
new Thread(deadLock1).start();
new Thread(deadLock2).start();
}
}
class DeadLock implements Runnable {
private boolean flag = false;
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
private static Object object1 = new Object();
private static Object object2 = new Object();
public void run() {
if (flag) {
synchronized (object1) {
System.out.println(Thread.currentThread().getName() + " get object1.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object2) {
System.out.println(Thread.currentThread().getName() + " get object2.");
}
}
} else {
synchronized (object2) {
System.out.println(Thread.currentThread().getName() + " get object2.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object1) {
System.out.println(Thread.currentThread().getName() + " get object1.");
}
}
}
}
}
13、反射:通过classloader加载类,标准做法如下:
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) cl = MyClass.class.getClassLoader(); // fallback
Class clazz = cl.loadClass(name);
14、文件大小限制
错误做法:
public int getFileSize(File f) {
long l = f.length();
return (int) l;
}
正确做法如下:
不支持传递超过2GB的文件. 最好的做法是对长度进行检查, 溢出时抛出异常
public int getFileSize(File f) {
long l = f.length();
if (l > Integer.MAX_VALUE) throw new IllegalStateException("int overflow");
return (int) l;
}
15、线程sleep中断
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
or
while (true) {
if (Thread.currentThread().isInterrupted()) break;
}
16、开发中常用术语解释
java的几种对象(PO,VO,DAO,BO,POJO)解释
一、PO:persistant object 持久对象,可以看成是与数据库中的表相映射的java对象。最简单的PO就是对应数据库中某个表中的一条记录,多个记录可以用PO的集合。PO中应该不包含任何对数据库的操作。
二、VO:value object值对象。通常用于业务层之间的数据传递,和PO一样也是仅仅包含数据而已。但应是抽象出的业务对象,可以和表对应,也可以不,这根据业务的需要.个人觉得同DTO(数据传输对象),在web上传递。
三、DAO:data access object 数据访问对象,此对象用于访问数据库。通常和PO结合使用,DAO中包含了各种数据库的操作方法。通过它的方法,结合PO对数据库进行相关的操作。
四、BO:business object 业务对象,封装业务逻辑的java对象,通过调用DAO方法,结合PO,VO进行业务操作。
五、POJO:plain ordinary java object 简单无规则java对象,我个人觉得它和其他不是一个层面上的东西,VO和PO应该都属于它。
17、多线售票系统:
class TicketSeller implements Runnable {
private int ticketCount = 10;
@Override
public void run() {
while (ticketCount > 0) {
synchronized (this) {
if (ticketCount > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ " sell ticket: " + ticketCount--);
}
}
}
}
}
public class Demo01 {
public static void main(String[] args) {
TicketSeller ticketSeller = new TicketSeller();
new Thread(ticketSeller, "Thread A").start();
new Thread(ticketSeller, "Thread B").start();
new Thread(ticketSeller, "Thread C").start();
new Thread(ticketSeller, "Thread D").start();
}
}
测试结果:
Thread A sell ticket: 10
Thread A sell ticket: 9
Thread D sell ticket: 8
Thread D sell ticket: 7
Thread D sell ticket: 6
Thread C sell ticket: 5
Thread C sell ticket: 4
Thread C sell ticket: 3
Thread B sell ticket: 2
Thread B sell ticket: 1
18、中断处理
class TicketSeller implements Runnable {
@Override
public void run() {
try {
System.out.println("线程启动");
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("线程被中断");
// e.printStackTrace();
}
}
}
public class Demo01 {
public static void main(String[] args) throws InterruptedException {
TicketSeller ticketSeller = new TicketSeller();
Thread thread = new Thread(ticketSeller, "Thread A");
thread.start();
System.out.println("====主线程执行===");
Thread.sleep(1000);
// thread.interrupt();
System.out.println("线程被中断否:" + thread.isInterrupted());
thread.interrupt();
System.out.println("线程被中断否:" + thread.isInterrupted());
System.out.println("线程被中断否2:" + thread.isInterrupted());
System.out.println("主线程是否被中断:" + Thread.interrupted());
System.out.println("====主线程结束===");
}
}
测试结果:
====主线程执行===
线程启动
线程被中断否:false
线程被中断否:true
线程被中断否2:true
主线程是否被中断:false
线程被中断
====主线程结束===
结论:
interrupt中断该线程, isInterrupted检查该线程是否被中断, interrupted检查当前线程是否被中断。
相关文章推荐
- Java基础知识回顾-5 常用基础类
- jsp/java web基础知识回顾
- java基础知识回顾(一)
- java基础知识回顾之---java String final类普通方法
- java基础知识回顾(四)
- java基础知识回顾之面向对象
- java基础知识回顾
- JavaSE第十二讲:Java基础知识回顾
- java基础知识回顾之关键字
- java基础知识回顾
- Java科普之基础知识回顾
- Java基础知识回顾-8
- java基础知识回顾1
- Java基础知识回顾-9
- Java基础知识回顾-6
- 黑马程序员——java语言基础知识回顾(二)
- 黑马程序员——java语言基础知识回顾(四)
- JavaSE第十三讲:Java基础知识回顾 续
- java基础知识回顾(三)
- java基础知识回顾