創建4個線程,兩個對j加一,兩個對j減一(j兩同兩內)


package multithread;

public class MyThread {
    //j變量私有
    private int j;
    //同步的+1方法
    private synchronized void add(){
        j++;
        System.out.println(Thread.currentThread().getName()+"----------> "+j);
    }
    //同步的-1方法
    private synchronized void subtract(){
        j--;
        System.out.println(Thread.currentThread().getName()+"----------> "+j);
    }
    //實現Runnable接口的內部加類
    class Add implements Runnable{

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                add();
            }
        }
    }
    //實現Runnable接口的內部減類
    class Subtract implements Runnable{
        
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                subtract();
            }
        }
    }
    
    public static void main(String[] args) {
        //創建外部類和內部類的實例
        MyThread mt = new MyThread();
        Add add = mt.new Add();
        Subtract subtract = mt.new Subtract();
        //循環啟動4個線程
        for (int i = 0; i < 2; i++) {
            Thread t = new Thread(add);
            t.start();
            t = new Thread(subtract);
            t.start();
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM