java - 我的java代码不同步

标签 java multithreading synchronization

class MultiplyTable1 {
    synchronized void printTable(int n) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(n * i);
            try {
                Thread.sleep(500);
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
}

class ThreadOne1 extends Thread {
    MultiplyTable1 mtObj = new MultiplyTable1();

    public void run() {
        mtObj.printTable(2);
    }
}

class ThreadTwo2 extends Thread {
    MultiplyTable1 mtObj = new MultiplyTable1();

    public void run() {
        mtObj.printTable(100);
    }
}

public class ThreadDemoDupe {

    public static void main(String[] args) {
        ThreadOne1 t1 = new ThreadOne1();
        ThreadTwo2 t2 = new ThreadTwo2();
        t1.start();
        t2.start();
    }
}

输出:

100
2
200
4
300
6
8
400
10
500

我的代码应该是什么来获得输出:

2
4
6
8
10
100
200
300
400
500

100
200
300
400
500
2
4
6
8
10

我没有更多细节可提供。

最佳答案

您正在创建两个单独的 MultiplyTable1 对象。 同步实例方法有效地使用:

synchronized (this) {
    ...
}

因此,如果您在两个不同的对象上调用该方法,它们仍然可以并行运行。要查看同步的效果,您需要在公共(public)对象上进行同步。您可以通过将其更改为不在 MultiplyTable1 对象本身上同步来实现此目的,或者您可以为两个线程提供相同的 MultiplyTable1 对象。例如:

class MultiplyTable1 {
    synchronized void printTable(int n) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(n*i);
            try {
                Thread.sleep(500);
            }
            catch (InterruptedException e) {
                System.out.println(e);
            }
        }
    }
}

// Prefer implementing Runnable over extending Thread.
// In reality I'd only have a single class and parameterize
// the value passed to the printTable method, but...
class Runnable1 implements Runnable {
    private final MultiplyTable1 table;

    Runnable1(MultiplyTable1 table) {
        this.table = table;
    }

    @Override public void run() {
        table.printTable(2);
    }
}

class Runnable2 implements Runnable {
    private final MultiplyTable1 table;

    Runnable2(MultiplyTable1 table) {
        this.table = table;
    }

    @Override public void run() {
        table.printTable(100);
    }
}

public class ThreadDemoDupe {
    public static void main(String[] args) {
        MultiplyTable1 table = new MultiplyTable1();
        Thread t1 = new Thread(new Runnable1(table));
        Thread t2 = new Thread(new Runnable2(table));
        t1.start();
        t2.start();
    }
}

关于java - 我的java代码不同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22434266/

相关文章:

java - 在 eclipse SWT 中执行代码之前 setVisible()

java - 如何将多个CA添加到tomcat中的信任库

java - 从 YANG 数据模型生成 XML RPC NETCONF 请求的标准方法是什么

java - 首先安全地使用 AtomicInteger 检查

multithreading - COM接口(interface): Using STA instead of MTA

java - 无法在未调用 Looper.prepare() 的线程内创建处理程序

java - 安装hadoop并编写map reduce程序

javascript - AngularJS 等待超时功能完成后再继续

python - ElasticSearch 更新不是即时的,你如何等待 ElasticSearch 完成更新它的索引?

java - 在 Eclipse 中获取同步源时查看 svn 提交消息/注释