多线程

笔记:

并行:真正意义的同时进行

并发:根据时间片的交替,线程的“同时”进行(对单核来说)。多核时是可以实现真正的同时的。

两种实现进程的方法,最好使用实现接口(Runable接口)的方法。可以保留该类可以实现继承父类的能力


/**
 * 多线程的例子------并发,在一个线程处于阻塞时,另一个便会执行
 */
package com.mulXianCheng;

public class Demo1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Pig pig=new Pig(10);
		Bird bird=new Bird(10);
		
		//创建线程(每个对象都可以创建一个线程,本例选择了两个线程并发运行)
		Thread thread1=new Thread(pig);
		Thread thread2=new Thread(bird);
		//线程开启
		thread1.start();
		thread2.start();
	}

}

class Pig implements Runnable{
	int n=0;
	int times=0;
	public  Pig(int n) {
		// TODO Auto-generated constructor stub
		this.n=n;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true){
			try {
				Thread.sleep(800);
			} catch (Exception e) {
				// TODO: handle exception
			}
			++times;
			System.out.println("我是一个线程,正在输出第"+times+"个HelloWorld");
			if (times==n) {
				break;
			}
		}
	}
	
}


class Bird implements Runnable{
	int n=0;
	int res=0;
	int times=0;
	public Bird(int n){
		this.n=n;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true){
			try {
				Thread.sleep(1000);
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			res+=(++times);
			System.out.println("当前结果是:"+res);
			if (times==n) {
				System.out.println("最后结果是:"+res);
				break;
			}
		}
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值