线程同步机制——同步方法

package thread;
/*
 * 同步方法
 * 同步方法就是在方法前面修饰synchronized关键字的方法
 * synchronized void f(){
 *
 * }
 * 当某个对象调用了同步方法时,该对象上的其它同步方法必须等待该同步方法执行完毕后才执行。
 * 必须将每个能访问共享资源的方法修饰为synchronized,否则就会报错。
 */
public class ThreadSafeTest2 implements Runnable {
    int num=10;
    public static void main(String[] args) {
        ThreadSafeTest2 t=new ThreadSafeTest2();
        Thread tA=new Thread(t);
        Thread tB=new Thread(t);
        Thread tC=new Thread(t);
        Thread tD=new Thread(t);
        tA.start();
        tB.start();
        tC.start();
        tD.start();

    }
    public synchronized void doit() {//定义同步方法
        if(num>0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("tickets"+num--);
        }
        
    }

    @Override
    public void run() {
        while(true) {
            doit();//在run()中调用该同步方法
        }
        
    }

}

猜你喜欢

转载自blog.csdn.net/qq_41978199/article/details/80655864