线程同步机制——同步块synchronized

package thread;
/*
 * 线程同步机制
 * 同步块
 * 在java中提供了同步机制,可以有效防止资源冲突。
 * 同步机制使用synchronized关键字
 */
public class ThreadSafeTest1 implements Runnable{
    int num=10;
    public static void main(String[] args) {
        ThreadSafeTest1 t=new ThreadSafeTest1();
        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();
    }

    @Override
    public void run() {
        while(true){
            synchronized("") {
                if(num>0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("tickets"+num--);
                }
            }
        }
        
    }

}

猜你喜欢

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