小编Mob*_*eam的帖子

在Java中执行两个同步块

为什么Java中的两个不同线程无法同时执行两个同步块.

编辑

public class JavaApplication4 {

    public static void main(String[] args) {
        new JavaApplication4();
    }

    public JavaApplication4() {
        Thread t1 = new Thread() {

            @Override
            public void run() {
                if (Thread.currentThread().getName().equals("Thread-1")) {
                    test(Thread.currentThread().getName());
                } else {
                    test1(Thread.currentThread().getName());
                }
            }
        };
        Thread t2 = new Thread(t1);
        t2.start();
        t1.start();

    }

    public synchronized void test(String msg) {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
            }
            System.out.println(msg);
        }
    }

    public synchronized void test1(String …
Run Code Online (Sandbox Code Playgroud)

java multithreading

4
推荐指数
2
解决办法
3271
查看次数

标签 统计

java ×1

multithreading ×1