看java多线程核心编程一书,有个例子不解其意。
package controller;
public class CountOperate extends Thread {
public CountOperate(){
System.out.println("CountOperate---begin");
System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName());
System.out.println("this.getName()=" + this.getName());
System.out.println("CountOperate---end");
}
@Override
public void run(){
System.out.println("run---begin");
System.out.println("Thread.currentThread().getName()="
+ Thread.currentThread().getName());
System.out.println("this.getName()=" + this.getName());
System.out.println("run---end");
}
}
package Test;
import controller.CountOperate;
public class GetCurrentThreadRun {
public static void main(String[] args){
CountOperate countOperate = new CountOperate();
countOperate.start();
Thread t = new Thread(countOperate);
t.setName("a");
t.start();
}
}
自己试着编写运行了下,结果如下:
CountOperate—begin
Thread.currentThread().getName()=main
this.getName()=Thread-0
CountOperate—end
run—begin
Thread.currentThread().getName()=Thread-0
this.getName()=Thread-0
run—end
run—begin
Thread.currentThread().getName()=a
this.getName()=Thread-0
run—end
查找jdk的文档,里面这样说明:
public void start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
大意:Thread.start的调用的结果是(两条线程):当前线程调用另外一条线程的run方法(如上所示,当前线程main线程调用t的run方法)。
原来这样。
以前只是写简单的功能实现,多线程这方面的技术涉足少,如今大数据时代来临,更有必要了解,不能让这个成为我的遗憾。