java 并发编程 执行顺序_Java并发编程入门

多线程的执行顺序

在并发程序设计中,由于要关注到流水线的效率,会乱序执行,在Java多线程中,每个线程也不是按照顺序执行的。

public class Main {

public static void main(String[] args){

Thread thread=new Thread(new Runnable() {

public void run() {

System.out.println("hello");

}

});

thread.start();

System.out.println("Main");

}

}

以上程序的运行结果会出现:

Main

hello

这就说明在多线程中,代码运行的结果与代码被调用的顺序是无关的。以下程序更能说明:

public class Main {

public static void main(String[] args){

Thread thread1=new Thread(new TheThread());

Thread thread2=new Thread(new TheThread());

Thread thread3=new Thread(new TheThread());

thread1.start();

thread2.start();

thread3.start();

}

}

class TheThread implements Runnable{

public void run() {

for(int i=0;i<10;i++)

System.out.println(Thread.currentThread().getId()+":"+i);

}

}

以上程序的运行结果可以自己证明。

运行以上程序,查看结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值