zoukankan      html  css  js  c++  java
  • java关键字synchronized

    1、对于synchronized方法和synchronized块,一个线程访问时,其他线程可以访问此类的非synchronized方法或块,不能访问其他带synchronized的方法或块。

    举例如下:

    synchronized块:

    public class Thread2 {

    public void m4t1() {
    synchronized (this) {
    int i = 5;
    while (i-- > 0) {
    System.out.println(Thread.currentThread().getName() + " : " + i);
    try {
    Thread.sleep(2000);
    } catch (InterruptedException ie) {
    ie.printStackTrace();
    }
    }
    }
    }

    public void m4t2() {
    synchronized (this) {
    int i = 5;
    while (i-- > 0) {
    System.out.println(Thread.currentThread().getName() + " : " + i);
    try {
    Thread.sleep(2000);
    } catch (InterruptedException ie) {
    ie.printStackTrace();
    }
    }
    }
    }

    public static void main(String[] args) {
    final Thread2 myt2 = new Thread2();
    Thread t1 = new Thread(new Runnable() {
    public void run() {
    myt2.m4t1();
    }
    }, "t1");
    Thread t2 = new Thread(new Runnable() {
    public void run() {
    myt2.m4t2();
    }
    }, "t2");
    t1.start();
    t2.start();
    }
    }

    synchronized方法:

    public class Thread3 {

    public synchronized void m4t1() {

    int i = 5;
    while (i-- > 0) {
    System.out.println(Thread.currentThread().getName() + " : " + i);
    try {
    Thread.sleep(2000);
    } catch (InterruptedException ie) {
    ie.printStackTrace();
    }
    }

    }

    public synchronized void m4t2() {

    int i = 5;
    while (i-- > 0) {
    System.out.println(Thread.currentThread().getName() + " : " + i);
    try {
    Thread.sleep(2000);
    } catch (InterruptedException ie) {
    ie.printStackTrace();
    }
    }

    }

    public static void main(String[] args) {
    final Thread3 myt2 = new Thread3();
    Thread t1 = new Thread(new Runnable() {
    public void run() {
    myt2.m4t1();
    }
    }, "t1");
    Thread t2 = new Thread(new Runnable() {
    public void run() {
    myt2.m4t2();
    }
    }, "t2");
    t1.start();
    t2.start();
    }

  • 相关阅读:
    洛谷 P1236 算24点
    洛谷 P1483 序列变换
    洛谷 P2071 座位安排 seat.cpp/c/pas
    洛谷 P3079 [USACO13MAR]农场的画Farm Painting
    洛谷 P3912 素数个数
    洛谷 P1617 爱与愁的一千个伤心的理由
    洛谷 P1894 [USACO4.2]完美的牛栏The Perfect Stall
    hdu_5908_Abelian Period(暴力)
    hdu_4283_You Are the One(区间DP)
    hdu_5903_Square Distance(dp)
  • 原文地址:https://www.cnblogs.com/chengJAVA/p/5822358.html
Copyright © 2011-2022 走看看