多线程的同步和异步讲解案例

package com.dj;

public class SynTest {
    // 非同步 
    static void method(Thread thread) {
        System.out.println("begin0 " + thread.getName());
        try {
            Thread.sleep(3000);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        System.out.println("end " + thread.getName());
    }

    //同步方式一:同步方法 这个方法是同步的方法,每次只有一个线程可以进来
    synchronized static void method1(Thread thread) {
        System.out.println("begin1 " + thread.getName());
        try {
            Thread.sleep(3000);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        System.out.println("end " + thread.getName());
    }

    //同步方式二:同步代码块
    static void method2(Thread thread) {
        synchronized (SynTest.class) {
            System.out.println("begin2 " + thread.getName());
            try {
                Thread.sleep(3000);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            System.out.println("end " + thread.getName());
        }
    }

    //同步方式三:使用同步对象锁
    private static Object _lock1 = new Object();
    private static byte _lock2[] = {};//据说,此锁更可提高性能。源于:锁的对象越小越好 

    static void method3(Thread thread) {
        synchronized (_lock1) {
            System.out.println("begin3 " + thread.getName());
            try {
                Thread.sleep(3000);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            System.out.println("end " + thread.getName());
        }
    }

    public static void main(String[] args) { //启动3个线程,这里用了匿名类 
        for (int i = 0; i < 3; i++) {
            new Thread() {
                public void run() {
                    method(this);
                    method1(this);
                    method2(this);
                    method3(this);
                }
            }.start();
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Fee_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值