zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    response.redirect三种新页面转向方法
    respones.redirect 打开新的页面的两个方法
    临时表
    ODBC方式操作oracle数据库
    OLEDB方式操作oracle数据库
    oracle所有的乱码解决方案
    引用HM.Util.Ioc 的时候报错
    js webstrom中svn的配置及使用
    js vs2013中允许js访问json文件的解决方案
    Oracle 字符集常见字符集及解决方案
  • 原文地址:https://www.cnblogs.com/risuschen/p/12872734.html
Copyright © 2011-2022 走看看