简体   繁体   English

Java中的同步

[英]Synchronization in Java

-I want to print the output below by using synchronization technique in Java - 我想在Java中使用同步技术打印下面的输出

1
1
2
2
3
3
4
4
5
5

-I wrote the code below but I am getting a compile time error saying obj variable is not referenced - 我写了下面的代码,但我得到一个编译时错误,说没有引用obj变量

-obj variable is in the synchronization block in the run method -obj变量位于run方法的同步块中

-I created 2 threads Child1 and Child2 and shared obj between them - 我创建了2个线程Child1和Child2,并在它们之间共享obj

-How to make obj visible to synchronization block so that I can get desired output? - 如何使obj对同步块可见,以便我可以获得所需的输出?

package multi_threading;

public class inter_thread {
    boolean val=false;
    Thread t;
    public inter_thread(test_value obj,String msg){
        t=new Thread(obj,msg);
        t.start();
    }
}
class test_value implements Runnable{
    boolean val=false;
    public static void main(String args[]){
        test_value obj=new test_value();
        inter_thread obj1=new inter_thread(obj,"Child1"); 
        inter_thread obj2=new inter_thread(obj,"Child2");
        try{
            obj1.t.join();
            obj2.t.join();
        }catch(InterruptedException e){
            System.out.println("Interrupted");
        }
    }
public void run(){
    int i;
    synchronized(obj){
       for(i=1;i<=5;i++){
       System.out.println(i);
       obj.val=!obj.val;
           while(obj.val)
                try{
                    wait();
                }catch(InterruptedException e){
                    System.out.println("Interrupted");
                }
               notify();
        }
      }
    }
 }

I think the easiest way is to use a CyclicBarrier : 我认为最简单的方法是使用CyclicBarrier

public class SyncTask implements Runnable {
    private final CyclicBarrier barrier;

    public SyncTask(CyclicBarrier barrier) { this.barrier = barrier; }

    @Override
    public void run() {
        try {
            for (int i = 1; i <= 5; i++) {
                System.out.println(i);
                barrier.await();
            }
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(2);
        new Thread(new SyncTask(barrier)).start();
        new Thread(new SyncTask(barrier)).start();
    }
}

(Note that here the two tasks are not really alternating but run in parallel. But the CyclicBarrier forces them to wait for each other after each System.out.println ) (注意,这里的两个任务并不是真正交替,而是并行运行。但CyclicBarrier强制它们在每个System.out.println之后等待彼此)

Try this out...it worked for me! 尝试一下......它对我有用! Please add parentheses for while loop and restrict synchronized. 请为while循环添加括号并限制synchronized。

And to obtain obj, make it an instance variable so that run method can access it 要获取obj,请将其设为实例变量,以便run方法可以访问它

     class inter_thread {
    boolean val=false;
    Thread t;
    public inter_thread(test_value obj,String msg){
        t=new Thread(obj,msg);
        t.start();
    }
}
 public class test_value implements Runnable{
    boolean val=false;
    static test_value obj=new test_value();
    public static void main(String args[]){

        inter_thread obj1=new inter_thread(obj,"Child1"); 
        inter_thread obj2=new inter_thread(obj,"Child2");
    }
public void run(){
    int i;
       for(i=1;i<=5;i++){
       System.out.println(i);

       synchronized(obj){
        obj.val=!obj.val;
           while(obj.val){
                try{
                    wait();
                }catch(InterruptedException e){
                    System.out.println("Interrupted");
                }
           }
        notify();
        }
      }
    }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM