java基础---->多线程之synchronized(六)

时间:2021-10-04 13:29:27

  这里学习一下java多线程中的关于synchronized的用法。我来不及认真地年轻,待明白过来时,只能选择认真地老去。

synchronized的简单实例

一、 synchronized在方法上的使用

public class SynchronizedTest {
public static void main(String[] args) {
MyThreadB threadB = new MyThreadB();
new Thread(threadB, "T-1").start();
new Thread(threadB, "T-2").start();
} static class MyThreadB implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " before");
printString();
System.out.println(Thread.currentThread().getName() + " after");
} private synchronized void printString() {
for (int i = 0; i < 3; i++) {
try {
TimeUnit.SECONDS.sleep(i + 1);
System.out.println(Thread.currentThread().getName() + " , i = " + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

运行的一次结果如下:

T- before
T- before
T- , i =
T- , i =
T- , i =
T- after
T- , i =
T- , i =
T- , i =
T- after

如果去掉synchronized之后,一次的打印结果如下:

T- before
T- before
T- , i =
T- , i =
T- , i =
T- , i =
T- , i =
T- after
T- , i =
T- after

二、synchronized代码块的使用

public class SynchronizedTest {
public static void main(String[] args) {
MyThreadA threadA = new MyThreadA();
new Thread(threadA, "T-1").start();
new Thread(threadA, "T-2").start();
} static class MyThreadA implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " outside of synchronized.");
synchronized (this) {
for (int i = 0; i < 3; i++) {
try {
TimeUnit.SECONDS.sleep(i + 1);
System.out.println(Thread.currentThread().getName() + " , i = " + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}

一次的运行结果如下:

T- outside of synchronized.
T- outside of synchronized.
T- , i =
T- , i =
T- , i =
T- , i =
T- , i =
T- , i =

如果去掉synchronized之后,一次的打印结果如下:

T- outside of synchronized.
T- outside of synchronized.
T- , i =
T- , i =
T- , i =
T- , i =
T- , i =
T- , i =

友情链接