今天来练习一下synchronized
简单来利用synchronized实现一个字符串的交替打印
主要的实现设置一个全局的变量state,线程执行通过不断累加state,根据state对三取余的结果来判断该线程是否继续执行还是进入等待。并通过synchronized锁住一个共享变量lock来进行上锁。
最后创建三个线程并让其进入就绪态。
代码实现:
            
            
              java
              
              
            
          
          public class Test {
    private static final Object lock = new Object();
    private static volatile int state = 0;
    public static void main(String[] args) {
        Thread A = new Thread(new task("a", 0));
        Thread B = new Thread(new task("b", 1));
        Thread C = new Thread(new task("c", 2));
        A.start();
        B.start();
        C.start();
    }
    static class task implements Runnable {
        private String s;
        private int x;
        public task(String s, int x) {
            this.s = s;
            this.x = x;
        }
        @Override
        public void run() {
            while(true) {
                synchronized (lock) {
                    while (state % 3 != x) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(s);
                    state++;
                    lock.notifyAll();
                }
            }
        }
    }
}结果展示:结果会一直交替打印abc
