实习的时候发现多线程方面知识比较薄弱,这段时间在学习汪文君老师的《Java高并发编程实战》,并做一些学习笔记,供以后复习。
我们在单线程情况下执行两个方法,默认是按照顺序执行的,如下面的读写数据库操作:
public class TryConcurrency1 {
public static void main(String[] args) {
readFromDataBase();
writeDataToFile();
}
private static void readFromDataBase() {
//read data from database and handle it.
try {
println("Test1:"+"Begin read data from db.");
Thread.sleep(1000 * 3L);
println("Test1:"+"Read data done and start handle it.");
} catch (InterruptedException e) {
e.printStackTrace();
}
println("Test1:"+"The data handle finish and successfully.");
}
private static void writeDataToFile() {
try {
println("Test2:"+"Begin write data to file.");
Thread.sleep(1000 * 10L);
println("Test2:"+"Write data done and start handle it.");
} catch (InterruptedException e) {
e.printStackTrace();
}
println("Test2:"+"The data handle finish and successfully.");
}
private static void println(String message) {
System.out.println(message);
}
}
输出结果为:
如果我们要并行的读写数据库,那么我们就要用到多线程操作,如:
public class TryConcurrency1 {
public static void main(String[] args) {
Thread t=new Thread("read-Thread"){
@Override
public void run() {
println(Thread.currentThread().getName());//main
readFromDataBase();
}
};
t.start();
//通过匿名内部类的方式
new Thread("write-Thread"){
@Override
public void run() {
writeDataToFile();
}
}.start();
}
private static void readFromDataBase() {
//read data from database and handle it.
try {
println("Test1:"+"Begin read data from db.");
Thread.sleep(1000 * 3L);
println("Test1:"+"Read data done and start handle it.");
} catch (InterruptedException e) {
e.printStackTrace();
}
println("Test1:"+"The data handle finish and successfully.");
}
private static void writeDataToFile() {
try {
println("Test2:"+"Begin write data to file.");
Thread.sleep(1000 * 10L);
println("Test2:"+"Write data done and start handle it.");
} catch (InterruptedException e) {
e.printStackTrace();
}
println("Test2:"+"The data handle finish and successfully.");
}
private static void println(String message) {
System.out.println(message);
}
}
值得注意的是: 创建Thread并非一个线程,只有当启动之后才会成为一个线程。