先来一句总结。
因为一个线程只能启动一次,通过Thread实现线程时,线程和线程所要执行的任务是捆绑在一起的。也就使得一个任务只能启动一个线程,不同的线程执行的任务是不相同的,所以没有必要,也不能让两个线程共享彼此任务中的资源。
一个任务可以启动多个线程,通过Runnable方式实现的线程,实际是开辟一个线程,将任务传递进去,由此线程执行。可以实例化多个 Thread对象,将同一任务传递进去,也就是一个任务可以启动多个线程来执行它。这些线程执行的是同一个任务,所以他们的资源是共享。
两种不同的线程实现方式本身就决定了其是否能进行资源共享。
个人理解:网上很多文章讲述可以使用Runnable实现资源共享,当然有的使用继承Thread也可以,但我还是表示怀疑这种做法是否真的可以实现资源共享,在共享资源的过程中并没有使用同步字段,这样是否会引起资源冲突,还需进一步探讨,如有牛人解释,不胜感激!
看代码。
package test;
import java.util.ArrayList;
import java.util.List;
/**
@author BY QinLiang
Time:2018年5月9日
*/
public class TestThread extends Thread{
private static int i =0;
public synchronized void add(){
i++;
}
@Override
public synchronized void run() {
for (int i = 0; i < 100; i++) {
this.i++;
}
}
public static void main(String[] args) throws InterruptedException {
/* Runnable runnable = new Runnable() {
public void run() {
for (int i = 0; i < 100; i++) {
TestThread.i++;
}
}
};*/
ArrayList<Thread> threads = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Thread thread = new TestThread();
threads.add(thread);
thread.start();
}
while (true) {
if (allThreadTerminated(threads)) {// 所有线程运行结束
System.out.println(i);
break;
}
}
}
private static boolean allThreadTerminated(List<Thread> threads) {
for (Thread thread : threads) {
if (thread.isAlive()) {
return false;
}
}
return true;
}
}
实现runable接口的时候可以操作共享资源,只需要在run方法上加上锁即可。