通过继承Thread类实现多线程无法公用一个资源,通过实现接口可以实现共享一个资源
代码测试:
当使用接口实现多线程时:
public class helloworld {
public static void main (String[] args)
{
AA a=new AA();
new Thread(a,"a1").start();
new Thread(a,"a2").start();
new Thread(a,"a3").start();
new Thread(a,"a4").start();
}
}
class AA implements Runnable{
private int c=10;
public void run() {
while(true) {
if(c>0) {
System.out.println(Thread.currentThread().getName()+"and"+c--);
}
}
}
}
```
运行结果:
a2and7
a2and6
a2and4
a4and8
a4and2
a4and1
a3and9
a2and3
a1and5
结论:通过接口实现多线程共用了一个变量c;
当使用继承实现时:
public class helloworld {
public static void main (String[] args) {
new BB().start();
new BB().start();
}
}
class BB extends Thread{
private int c=10;
public void run() {
while(true) {
if(c>0) {
System.out.println(Thread.currentThread().getName()+"and"+c--);
}
}
}
}
运行结果:
Thread-0and10
Thread-1and10
Thread-0and9
Thread-1and9
Thread-0and8
Thread-1and8
Thread-0and7
Thread-1and7
Thread-0and6
Thread-1and6
Thread-0and5
Thread-1and5
Thread-0and4
Thread-1and4
Thread-0and3
Thread-1and3
Thread-0and2
结论:可见每个进程都独立创建了一个c 所以没用共用一个资源;
//个人学习,不对的地方请大佬指正