@Synchronized

@Synchronized,实现同步。

package com.huey.lombok;

import java.util.Date;

import lombok.Synchronized;

public class SynchronizedExample implements Runnable {

    @Override
    public void run() {
        sayHello();
    }

    @Synchronized
    public void sayHello() {
        System.out.println("hello, " + Thread.currentThread().getName() + "! Now is " + new Date());
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SynchronizedExample foo = new SynchronizedExample();
        new Thread(foo).start();    // [OUTPUT]: hello, Thread-0! Now is Sat Aug 01 10:55:08 CST 2015
        new Thread(foo).start();    // [OUTPUT]: hello, Thread-1! Now is Sat Aug 01 10:55:11 CST 2015
    }
}

 

相关文章:

  • 2021-08-07
  • 2021-05-19
  • 2021-10-21
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-23
  • 2022-12-23
相关资源
相似解决方案