Java實現多線程資源共享的方式

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();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章