Java實現多線程資源共享的方式
將共享變量設爲靜態成員變量
public class extendsTest extends Thread{
//共享資源變量
static int count = 0;
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+":"+this.count++);
}
}
public static void main(String[] args) {
extendsTest t1 = new extendsTest();
extendsTest t2 = new extendsTest();
t1.start();
t2.start();
}
}
利用Runnable接口
資源保存在Runnable接口中,然後只創建一份實現了Runnable接口的類的實例傳遞個需要共享資源的線程就可以了。
public class SyncTest implements Runnable{
//共享資源變量
int count = 0;
@Override
public void run() {
for (int i = 0; i < 100; i++) {
synchronized(this){System.out.println(Thread.currentThread().getName()+":"+this.count++);}
}
}
public static void main(String[] args) throws InterruptedException {
SyncTest syncTest1 = new SyncTest();
Thread thread1 = new Thread(syncTest1,"thread1");
Thread thread2 = new Thread(syncTest1, "thread2");
thread1.start();
thread2.start();
}
}