笔记:
并行:真正意义的同时进行
并发:根据时间片的交替,线程的“同时”进行(对单核来说)。多核时是可以实现真正的同时的。
两种实现进程的方法,最好使用实现接口(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;
}
}
}
}