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

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

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

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

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