Java学习:线程基础(二)

这篇博客探讨了Java中的线程基础知识,通过实例展示了如何创建两个线程,一个负责计算1到指定整数n的和,另一个线程则每秒在控制台上打印消息。实现了线程间的并发执行。
摘要由CSDN通过智能技术生成

两个线程交叉运行

案例:编写一个程序,该程序可以接受一个整数n,创建两个线程,一个线程计算从1+...+n并输出结果,另一个线程每隔一秒在控制台输出一句话。这两个工作要同时进行。

代码:

public class TwoThread {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Pig pig = new Pig();
		Bird brid = new Bird(10);
		Thread t1 = new Thread(pig);
		Thread t2 = new Thread(brid);
		t1.start();
		t2.start();

	}

}

class Pig implements Runnable {
	int n = 0;
	int times = 0;

	public void run() {
		while (true) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			times++;
			System.out.println("hello" + times);
			if (times == 10) {
				break;
			}
		}

	}
}

class Bird implements Runnable {
	int n = 0;
	int res = 0;
	int times = 0;

	public Bird(int n) {
		this.n = n;
	}

	public void run() {
		while (true) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			res += (++times);
			System.out.println("now is:" + res);
			if (times == n) {
				System.out.println("res is:" + res);
				break;
			}
		}

	}
}

执行结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值