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();
}
}