代码如下,比较简单,需要注意的几个要点是:
- 在没有调用 start() 之前,new Thread() 只是一个简单的java实例,不能称为线程;
- 调用start()后会立即返回,不会阻塞。
public class TryConcurrency {
public static void main(String[] args) {
new Thread("readFromDatabase"){
@Override
public void run() {
readFromDatabase();
}
}.start();
new Thread("writeToDatabase"){
@Override
public void run() {
writeToDatabase();
}
}.start();
}
public static void readFromDatabase(){
try {
System.out.println("begin read data from file");
Thread.sleep(1000*20L);
System.out.println("finish reading");
}catch (InterruptedException e){
e.printStackTrace();
}
}
public static void writeToDatabase(){
try {
System.out.println("begin write data to file");
Thread.sleep(1000*20L);
System.out.println("finish writing");
}catch (InterruptedException e){
e.printStackTrace();
}
}
}