java基础---->多线程之synchronized(六)
这里学习一下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-1 before
T-2 before
T-1 , i = 0
T-1 , i = 1
T-1 , i = 2
T-1 after
T-2 , i = 0
T-2 , i = 1
T-2 , i = 2
T-2 after
如果去掉synchronized之后,一次的打印结果如下:
T-1 before
T-2 before
T-1 , i = 0
T-2 , i = 0
T-1 , i = 1
T-2 , i = 1
T-1 , i = 2
T-1 after
T-2 , i = 2
T-2 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-2 outside of synchronized.
T-1 outside of synchronized.
T-2 , i = 0
T-2 , i = 1
T-2 , i = 2
T-1 , i = 0
T-1 , i = 1
T-1 , i = 2
如果去掉synchronized之后,一次的打印结果如下:
T-1 outside of synchronized.
T-2 outside of synchronized.
T-2 , i = 0
T-1 , i = 0
T-2 , i = 1
T-1 , i = 1
T-1 , i = 2
T-2 , i = 2
作者:
huhx
出处: www.cnblogs.com/huhx
格言:你尽力了,才有资格说自己的运气不好。
版权:本文版权归作者huhx和博客园共有,欢迎转载。未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
出处: www.cnblogs.com/huhx
格言:你尽力了,才有资格说自己的运气不好。
版权:本文版权归作者huhx和博客园共有,欢迎转载。未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步