zoukankan      html  css  js  c++  java
  • synchronized关键字实现线程安全

    /**
    * Created by it on 2017/6/7.
    */
    public class MyThread extends Thread {
    private int val;
    private Service service;
    static RealExecu realExecu=new RealExecu();
    public MyThread(int v) {
    val = v;
    }
    public MyThread(Service service) {
    this.service = service;
    }
    //这种做法是非线程安全的
    public synchronized void print1(int v) throws InterruptedException {
    for (int i = 0; i < 100; i++) {
    Thread.sleep(100);
    System.out.print(v);
    }
    }

    public void print2(int v) throws InterruptedException {
    //线程安全
    synchronized (MyThread.class) {
    for (int i = 0; i < 100; i++) {
    Thread.sleep(100);
    System.out.print(v);
    }
    }
    }

    public void run() {

    try {
    realExecu.print(val);
    }

    //print1(val);}
    //print2(val);}

    catch (InterruptedException ie){

    }
    }
    }

    /**
    * Created by it on 2017/6/7.
    */
    public class ThreadTest {
    public static void main(String[] args) {
    MyThread m1 = new MyThread(1);
    MyThread m2 = new MyThread(2);

    m1.start();
    m2.start();
    }
    }
    print1方法上加上synchronized,没有起同步作用,是因为该方法被不同实例调用,实现同步可以使用print2方法,在类实例上加锁;
    print2方法等同于把方法放入一个类中,在mythread中定义静态类实例变量,以实现synchronized的同步作用
    public class RealExecu {
    public synchronized void print(int v) throws InterruptedException {
    for (int i = 0; i < 100; i++) {
    Thread.sleep(100);
    System.out.print(v);
    }
    }
    }
  • 相关阅读:
    Docker系列二:Docker的基本结构
    Codeforces 1013
    树形结构升级
    Codeforces 402 and 403 (Div. 2 and 1)
    Codeforces 342
    图论基础
    树形结构基础
    Codeforces 788 (Div. 1)
    NOIP/CSP-J/S初赛集锦
    树的重心
  • 原文地址:https://www.cnblogs.com/cindy-zhu/p/6957852.html
Copyright © 2011-2022 走看看