简单讲解java多线程执行过程测试分析
class 类名 extends Thread{
方法1;
方法2;
…
public void run(){
// other code…
}
属性1;
属性2;
…
}
</blockquote>先看一个简单的例子:
<blockquote>/**
* @author Rollen-Holt 继承Thread类,直接调用run方法
* */
class hello extends Thread {
public hello() {
}
public hello(String name) {
this.name = name;
}
public void run() {
for (int i = 0; i < 5; i ) {
System.out.println(name "运行 " i);
}
}
public static void main(String[] args) {
hello h1=new hello("A");
hello h2=new hello("B");
h1.run();
h2.run();
}
private String name;
}
A运行 0
A运行 1
A运行 2
A运行 3
A运行 4
B运行 0
B运行 1
B运行 2
B运行 3
B运行 4
我们会发现这些都是顺序执行的,说明我们的调用方法不对,应该调用的是start()方法。
当我们把上面的主函数修改为如下所示的时候:
<blockquote>public static void main(String[] args) {hello h1=new hello("A");
hello h2=new hello("B");
h1.start();
h2.start();
}
</blockquote>
然后运行程序,输出的可能的结果如下:
A运行 0
B运行 0
B运行 1
B运行 2
B运行 3
B运行 4
A运行 1
A运行 2
A运行 3
A运行 4
因为需要用到CPU的资源,所以每次的运行结果基本是都不一样的,呵呵。
注意:虽然我们在这里调用的是start()方法,但是实际上调用的还是run()方法的主体。
那么:为什么我们不能直接调用run()方法呢?
我的理解是:线程的运行需要本地操作系统的支持。
如果你查看start的源代码的时候,会发现:
<blockquote>public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0 || this != me)
throw new IllegalThreadStateException();
group.add(this);
start0();
if (stopBeforeStart) {
stop0(throwableFromStop);
}
}
private native void start0();</blockquote>
您可能感兴趣的文章:
经典Java线程面试题70道
Java程序多线程测试笔记
java多线程编程测试笔记
php和java有什么区别
超详细的Java多线程教程
学习单元测试,告别祈祷式编程
简单讲解java多线程执行过程测试分析
python gil是什么
python c 和java的区别有哪些
Go 并发编程的思考