第一段代码 没有并行
public void doListen(){
try {
Thread.sleep(5000);
System.out.println("听力完成:"+System.currentTimeMillis()+":"+Thread.currentThread().getName());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doWalk(){
new Thread("子线程") {
public void run() {
try {
Thread.sleep(5000);
System.out.println("散步完成:"+System.currentTimeMillis()+":"+Thread.currentThread().getName());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
public static void main(String[] args) {
System.out.println("开始工作:"+System.currentTimeMillis());
Abc abc=new Abc();
long start=System.currentTimeMillis();
abc.doListen();
abc.doWalk();//
Abc abc_1=new Abc();
abc_1.doWalk();//
long end=System.currentTimeMillis();
System.out.println(end-start);
}
第二段实现并行的代码
public class MyListenThread extends Thread{
private Work work;
public MyListenThread(Work work) {
this.work=work;
}
@Override
public void run() {
work.doListen();
}
}
public class Work {
public void doSee(){
try {
System.out.println("阅读开始");
Thread.sleep(5000);
System.out.println("阅读完成:"+System.currentTimeMillis()+":"+Thread.currentThread().getName());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doListen(){
try {
System.out.println("听力开始");
Thread.sleep(5000);
System.out.println("听力完成:"+System.currentTimeMillis()+":"+Thread.currentThread().getName());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Test {
public static void main(String[] args) {
Work work=new Work();
//Thread.sleep(5000);如果调用来自同一个对象则不能并行,需要另外创建work1
//work.doSee();
MyListenThread mt=new MyListenThread(work);
mt.start();
Work work1=new Work();
work1.doSee();
}
}