在java中两个线程同时运行是怎么变化的

来源:互联网 发布:网络机顶盒必装软件 编辑:程序博客网 时间:2024/06/05 01:06

在线程运行中,两个线程同时运行的情况是很平常的,下面我用一个案例来说明一下两个线程同时运行时,线程状态的变化情况:

代码如下:

/* * 功能:两个线程同时运行是如何变化的 * 作者:zyj0813 * 案例:编写一个程序,该程序可以接受一个整数n,创建两个线程, * 一个线程计算从1+....+n并输出结果, * 另一个线程每隔一秒在控制台输出“我是一个线程,正在输出第i个hello world”。 */package com.test2;public class Demo2_5 {public static void main(String[] args) {Bird bird=new Bird(10);Pig pig=new Pig(10);//启动线程Thread t1=new Thread(bird);Thread t2=new Thread(pig);t1.start();t2.start();}}//创建一个猪类来打印class Pig implements Runnable{int times=0;int n=0;public Pig(int n){this.n=n;}public void run(){while(true){try {//时间延迟一秒Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}times++;System.out.println("我是一个线程,正在输出第"+times+"个 hello world!!!");if(times==n){break;}}}}//创建一个鸟类,来数数class Bird implements Runnable{int times=0;int res=0;int n=0;public Bird(int n){this.n=n;}public void run(){while(true){try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}res+=(++times);System.out.println("第"+times+"次计算结果:"+res);if(times==n){System.out.println("最终结果:"+res);break;}}}}

运行结果:(可以看出两个进程同时运行,输出的结果并不是按照某个固定的顺序进行的,是随机产生的,无规律可言)


阅读全文
1 0
原创粉丝点击