• 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

  • 相关阅读:
    POJ2299--树状数组求逆序数
    每周总结
    2016湖南省赛--A题--2016
    ACM暑期训练总结
    jQuery实现拖动布局并将排序结果保存到数据库
    TP3.2整合kindeditor
    TP3.2整合uplodify文件上传
    Sublime Text3 使用
    ThinkPHP AJAX分页及JS缓存的应用
    Thinkphp分页类使用
  • 原文地址:https://www.cnblogs.com/risuschen/p/12872734.html
Copyright © 2020-2023  润新知