Java 基本同步线程

标签 java multithreading synchronized

<分区>

我正在学习 Java,但在同步方面遇到了麻烦。我想打印来自许多 Java 线程的数字列表,并让每个线程按顺序运行。我在使用同步时遇到问题,因为我不太了解。能帮忙看懂吗?

我希望输出能够看到这一点,但有时线程顺序错误。我想要:

1-thread1
2-thread2
3-thread1
4-thread2
5-thread1
6-thread2
...
48-thread2
49-thread1

我的破解代码:

public class ManyThreadsAdd {
    public static int index = 0;

    public static void main(String[] args) {
        ManyThreadsAdd myClass = new ManyThreadsAdd();
        Thread thread1 = new Thread(myClass.new RunnableClass());
        Thread thread2 = new Thread(myClass.new RunnableClass());

        thread1.start();
        thread2.start();
    }

    class RunnableClass implements Runnable {
        public synchronized void run() {
            while (index < 49) {
                try {
                    Thread.sleep(100);
                    System.out.println(index+"-" +Thread.currentThread());
                    index = index + 1;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

最佳答案

这取决于你想做什么。

交替打印顺序的一种简单方法是在同一对象上进行同步,在这种情况下,您可以使用索引或任何其他对象。

public class ManyThreadsAdd {
    public static AtomicInteger index = new AtomicInteger(0);

    public static void main(String[] args) {
        ManyThreadsAdd myClass = new ManyThreadsAdd();
        Thread thread1 = new Thread(myClass.new RunnableClass());
        Thread thread2 = new Thread(myClass.new RunnableClass());

        thread1.start();
        thread2.start();
    }

    class RunnableClass implements Runnable {
        public void run(){
            synchronized(index){
                while(index.get() < 49){
                    try {
                      Thread.sleep(100);
                      System.out.println(index.get()+"-" +Thread.currentThread());
                      index.incrementAndGet();
                      index.notify();
                      index.wait();
                    } catch (InterruptedException e) {
                      e.printStackTrace();
                    }
                }
            }
        }
    }
}

关于Java 基本同步线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26406620/

相关文章:

java - 如何使用 JDBC 插入局部变量 MySQL

C#.net 4并行编程

java - 是否可以显式使用 Java 内在锁?

java - 访问来自不同类的变量

java - XA模式下Ehcache无法将数据溢出到磁盘(NotSerializedException)

java - Spring @ExceptionHandler 和多线程

java - 我是否需要使用 BufferedWriter 和 FileWriter 在将数据写入同一文件时实现同步?

java - 当同步方法正在执行时,非同步方法是否会阻塞

java - 何时刷新 BufferedWriter

php - “Serialization of '在Symfony应用程序中调用\Threaded类(pthread)时关闭' is not allowed”