首页 > 编程语言 > 详细

Java基础之线程4-线程同步

时间:2020-05-11 23:31:30      阅读:68      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 

如何保证多个线程多同一个资源的共享透明化:

一个有问题的多线程的例子::

public class TestSync implements Runnable{
Timer timer = new Timer();
public static void main(String[] args) {
TestSync testSync = new TestSync();
Thread thread1 = new Thread(testSync);
Thread thread2 = new Thread(testSync);
thread1.start();
thread2.start();

}
@Override
public void run() {
timer.add(Thread.currentThread().getName());
}
}

class Timer{
private static int num = 0;
public void add(String name){
num++;
try {
Thread.sleep(1);
}catch (InterruptedException e){}
System.out.println(name + ",你是第" + num + "个执行timer的线程");
}
}

上面的例子共享Timer对象, 执行的输出结果为:

  Thread-0,你是第2个执行timer的线程
  Thread-1,你是第2个执行timer的线程

 

解决方法一:

将下面的执行方法锁住,保证原子性--

synchronized (this) {
num++;
    try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
System.out.println(name + ",你是第" + num + "个执行timer的线程");
}

或者

public synchronized void add(String name) {

num++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
System.out.println(name + ",你是第" + num + "个执行timer的线程");

}

 

再执行测试类,结果就对了。

执行结果:

Thread-0,你是第1个执行timer的线程
Thread-1,你是第2个执行timer的线程

Process finished with exit code 0

 

Java基础之线程4-线程同步

原文:https://www.cnblogs.com/risuschen/p/12872734.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!