java多线程调用对象方法

/**

  • @author :lig

  • @date :Created in 2022/1/20 14:40

  • @description: 多线程调用方法使用syncronized能够实现阻塞效果

  • @modified By:

  • @version: $
    */
    public class TestSyncronized {
    private int i = 0;
    private void helloOne(){
    synchronized (this){
    i++;
    System.out.println("当前线程是-----"+Thread.currentThread().getName()+",对应的i值是:"+i);
    }
    }

    public static void main(String[] args) {
    TestSyncronized testSyncronized = new TestSyncronized();
    for (int i = 0; i < 10000; i++) {
    new Thread(()->{
    testSyncronized.helloOne();
    }).start();
    }
    try {
    Thread.sleep(3000);
    System.out.println(testSyncronized.i);
    System.out.println("main执行结束");
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }

posted @ 2022-01-20 15:21  雩娄的木子  阅读(371)  评论(0编辑  收藏  举报