参照代码。
线程和进程就像父级与子级的关系,一个进程可以包含一个或者多个线程。进程主要是负责保护和管理资源,而线程主要负责是CPU执行代码的过程。
我们运行下面的代码
public class Admission {
public static void main(String[] args) {
System.out.println("A、B两队球员开始入场……");
A a=new A();
a.start();
B b=new B();
b.start();
}
}
class A extends Thread {
public void run() {
for (int i = 1; i <= 11; i++) {
System.out.println("a"+ i);
}
}
}
class B extends Thread {
public void run() {
for (int i = 1; i <= 11; i++) {
System.out.println("b"+ i);
}
}
}
我们会得到,有顺序的进场,先是A队的,从1到11,再到B队的1到11
但是我们参照下面一个代码
public class Pool {
int capacity = 100;
public synchronized boolean drainage(int value) {
if (capacity == 0) {
return false;
} else {
capacity -= value;
capacity = capacity < 0 ? 0 : capacity;
System.out.println("水池还剩" + capacity + "升水");
return true;
}
}
public void startThread() {
Thread a = new Outfall("A", 1);
Thread b = new Outfall("B", 2);
Thread c = new Outfall("C", 3);
a.start();
b.start();
c.start();
}
class Outfall extends Thread {
String name;
int value;
public Outfall(String name, int value) {
this.name = name;
this.value = value;
}
public void run() {
while (drainage(value)) {
System.out.println(name + "排水口完成排水");
}
}
}
public static void main(String[] args) {
Pool p = new Pool();
p.startThread();
}
}
我们发现,此时的abc三个口,在争先进行。a执行一次排水1升,b是排2升,c三升,原本游泳池100升水。先是a口说“我排水排一次了,游泳池现在还剩99(100-1)升水”,然后是c说“我排水排一次了,游泳池现在还剩96(99-3)升水”,然后是b排两升水。这个并不顺序,也可能同一时间报告。跟我们建立线程的先后无所谓。
这是因为,这个是一个进程的3个线程。而最初的是不同的进程。
第一个代码,我们使用a.start()方法,再用b.start()方法。此时,到b的时候,已经完了。而第二个代码,是abc一起干活。简单来说,就是把一根稻谷放到稻谷脱壳机和把几个稻谷放进去的区别。栈嘛。
这是对线程和进程的区分。
代码来自于我的大学老师,我把我解读的结果发到网上,一是自律,二是找动力。本文章不允许可以转载,但是你可以自己用。好好学习。