有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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();
    }
}

有没有一种方法可以将每个块称为“原子”呢?意思是“一条线规则!!”总是在“我在1!!!”之前出现

Output example image

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

提前谢谢


共 (0) 个答案