通用同步代码块 [无对象锁定]



这是我想出的一个简单代码来说明我的问题:

public class Main {
    public static void main(String[] args) {
        int sleepTime = 10, N = 1000;
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < N; i++) {
                { //BLOCK 1
                    //I want these two instructions to run one right after the other one
                    System.out.println("Thread one rules!!");
                    System.out.println("Im in 1!!!n");
                }
                try {
                    Thread.sleep(sleepTime); //I also tried yield
                } catch (InterruptedException e) {}
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < N; i++) {
                { //BLOCK 2
                    //I want these two instructions to run one right after the other one
                    System.out.println("Thread two rules!!");
                    System.out.println("Im in 2!!!n");
                }
                try {
                    Thread.sleep(sleepTime); //I also tried yield
                } catch (InterruptedException e) {}
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }
}

有没有办法让每个块都被称为"原子"?意思是"线程一规则!!"将永远出现在"Im in 1!!"之前

输出示例图像

我不想在同步块中使用任何虚拟对象,也不想使用任何等待/通知语句。我想要一个与数百个线程一起运行的实现。我尝试使用将公共对象作为参数的同步语句 mySocketServer,但它开始给我带来计时问题。

提前致谢

最相关的方法是使用单个调用:

System.out.println("<first line>n<second line>");

顺便说一下,我认为时间不应该受到额外的同步块的影响。在任何情况下,您都可以使用System.out

synchronized(System.out) {
...
} 

这绝对不会影响时间。像println((这样的PrintStream方法已经包含了这种同步,因此这个额外的同步块将优化锁定。

不,您必须锁定 System.out 以防止线程一规则!!线程两个规则!!

即使锁定每个块也将允许两个线程同时写入System.out。

您需要以一种方式或另一种方式锁定对象。标准做法是拥有一个共享的可访问对象(如 public Object sharedLock = new Object() 并在syncrhonized块中使用它。

最新更新