我在这里研究多线程操作。但我目前对主方法执行顺序感到怀疑。请向我解释这些,问题标记在下面。
这是我正在研究的一个简单的程序
public class HelloWorld implements Runnable {
private Thread t;
private String threadname;
HelloWorld(String name){
threadname= name;
System.out.println("Create " +threadname);
}
public void run() {
System.out.println("Running " +threadname);
try {
for(int i=4; i>0;i--) {
System.out.println("Thread" +threadname +", "+i);
Thread.sleep(50);
}
}catch(InterruptedException e) {
System.out.println("Thread" +threadname +"interrupted ");
}
System.out.println("Thread" +threadname +"exiting ");
}
public void start() {
System.out.println("Starting " +threadname);
if(t==null)
{
t=new Thread(this, threadname);
t.start();
}
}
public static void main(String[] args) {
HelloWorld obj1= new HelloWorld ("Thread-1");
obj1.start();
HelloWorld obj2= new HelloWorld ("Thread-2");
obj2.start();
}
}
实际结果
Create Thread-1
Starting Thread-1
Create Thread-2
Starting Thread-2
Running Thread-1
ThreadThread-1, 4
Running Thread-2
ThreadThread-2, 4
ThreadThread-2, 3
ThreadThread-1, 3
ThreadThread-1, 2
ThreadThread-2, 2
ThreadThread-1, 1
ThreadThread-2, 1
ThreadThread-2exiting
ThreadThread-1exiting
我的问题:
Create Thread-1
Starting Thread-1
Create Thread-2(why here will switch from 1 to 2)
Starting Thread-2
Running Thread-1
ThreadThread-1, 4
Running Thread-2(At here, I understand the thread is switch when Thread.sleep(50) is being executed;)
ThreadThread-2, 4
ThreadThread-2, 3
ThreadThread-1, 3
ThreadThread-1, 2
ThreadThread-2, 2
ThreadThread-1, 1
ThreadThread-2, 1
ThreadThread-2exiting
ThreadThread-1exiting
问:为什么这里会从1切换到2? 主方法中的 2 个对象是否同时运行?
这是因为您使用的是多线程和多线程 提供并行执行。
在 main 方法中,您已经启动了两个子线程 obj1.start(( 和 obj2.start((。直到 obj1.start(( 只有一个子线程(主线程是父线程(。但是当你启动第二个子线程obj2.start((时,现在有两个子线程正在并行执行,这就是切换发生的原因。这两个线程将具有单独的执行路径,并将并行运行。
此外,由于 CPU 正在使用线程调度算法(轮循机制等(,因此会发生切换。