zoukankan      html  css  js  c++  java
  • 【多线程】Java并发中的锁(草稿)

    可重入锁Synchronized

     1 public class DemoTest {
     2     public static void main(String[] args) {
     3         final DemoTest demoTest = new DemoTest();
     4 
     5         Thread thread1 = new Thread(new Runnable() {
     6             @Override
     7             public void run() {
     8                 System.out.println(Thread.currentThread().getName() + "run");
     9                 demoTest.method1();
    10             }
    11         });
    12         thread1.setName("thread-1");
    13         thread1.start();
    14 
    15         Thread thread2 = new Thread(new Runnable() {
    16             @Override
    17             public void run() {
    18                 System.out.println(Thread.currentThread().getName() + "run");
    19                 demoTest.method2();
    20             }
    21         });
    22         thread2.setName("thread-2");
    23         thread2.start();
    24     }
    25 
    26     public synchronized void method1() {
    27         System.out.println("method1 run in" + Thread.currentThread().getName());
    28         try {
    29             Thread.sleep(1000);
    30             method2();
    31         } catch (InterruptedException e) {
    32             e.printStackTrace();
    33         }
    34     }
    35 
    36     public synchronized void method2() {
    37         System.out.println("method2 run in" + Thread.currentThread().getName());
    38     }
    39 
    40 }

    运行结果

    thread-1run
    method1 run inthread-1
    thread-2run
    method2 run inthread-1
    method2 run inthread-2

    11

  • 相关阅读:
    Java ArrayList,LinkedList使用
    Vue 使用axios分片上传
    Vue 中Axios 使用
    Vue 自定义组件
    Java IO系统--RandomAccessFile
    Java IO系统--字符流
    Java String类
    静态导入(static import)
    枚举(Enum)
    Java 可变参数
  • 原文地址:https://www.cnblogs.com/andy-songwei/p/15030122.html
Copyright © 2011-2022 走看看