有 Java 编程相关的问题?

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

多线程如何在Java中实现同步?

我有一个关于多线程的作业,我需要一些帮助

我有一个无法更改的Ressource类

public class Ressource {
    public int val;
    public void incr() {
        val++;

    }
    public void decr() {
        val--;

    }

我有我的主课

public class TwoThreads {
    public static Ressource res = new Ressource();
    public static void main(String[] args)  {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0; i < 100; i++){
                    res.incr();
                }
                System.out.println(res.val);
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0; i < 100; i++){
                    res.decr();
                }
                System.out.println(res.val);
            }
        });
        t1.start();
        t2.start();

    }
}

我尝试在重写方法中使用synchronized,但没有成功。我知道如果我用

 public synchronized void incr() {
        val++;

    }

它会起作用,但我不应该在Resources类中更改任何内容。有什么想法吗


共 (1) 个答案

  1. # 1 楼答案

    i want to increase to 100 and then decrease to 0.First t1 should run and when its finished should t2 start.But i have to do it in the main method.

    您可以按如下方式操作:

    t1.start();
    t1.join();
    t2.start();
    

    演示:

    class Ressource {
        public int val;
    
        public void incr() {
            val++;
    
        }
    
        public void decr() {
            val ;
    
        }
    }
    
    public class Main {
        public static Ressource res = new Ressource();
    
        public static void main(String[] args) throws InterruptedException {
            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 100; i++) {
                        System.out.println(res.val);
                        res.incr();
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 100; i++) {
                        System.out.println(res.val);
                        res.decr();
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(res.val);
                }
            });
            t1.start();
            t1.join();
            t2.start();
        }
    }