Вопрос по java, multithreading – Что означает «синхронизированный»?

893

У меня есть несколько вопросов, касающихся использования и значенияsynchronized ключевое слово.

  • What is the significance of the synchronized keyword?
  • When should methods be synchronized?
  • What does it mean programmatically and logically?
Error: User Rate Limit ExceededHow does synchronized work in Java Marian Paździoch
Error: User Rate Limit Exceededstackoverflow.com/questions/40471/java-hashmap-vs-hashtable limc

Ваш Ответ

15   ответов
-6

3

class MyRunnable implements Runnable {
    int var = 10;
    @Override
    public void run() {
        call();
    }

    public void call() {
        synchronized (this) {
            for (int i = 0; i < 4; i++) {
                var++;
                System.out.println("Current Thread " + Thread.currentThread().getName() + " var value "+var);
            }
        }
    }
}

public class MutlipleThreadsRunnable {
    public static void main(String[] args) {
        MyRunnable runnable1 = new MyRunnable();
        MyRunnable runnable2 = new MyRunnable();
        Thread t1 = new Thread(runnable1);
        t1.setName("Thread -1");
        Thread t2 = new Thread(runnable2);
        t2.setName("Thread -2");
        Thread t3 = new Thread(runnable1);
        t3.setName("Thread -3");
        t1.start();
        t2.start();
        t3.start();
    }
}

Without Synchronized keyword

    Current Thread Thread -1 var value 11
    Current Thread Thread -2 var value 11
    Current Thread Thread -2 var value 12
    Current Thread Thread -2 var value 13
    Current Thread Thread -2 var value 14
    Current Thread Thread -1 var value 12
    Current Thread Thread -3 var value 13
    Current Thread Thread -3 var value 15
    Current Thread Thread -1 var value 14
    Current Thread Thread -1 var value 17
    Current Thread Thread -3 var value 16
    Current Thread Thread -3 var value 18

Current Thread Thread -1 var value 11
Current Thread Thread -2 var value 11
Current Thread Thread -1 var value 12
Current Thread Thread -2 var value 12
Current Thread Thread -1 var value 13
Current Thread Thread -2 var value 13
Current Thread Thread -1 var value 14
Current Thread Thread -2 var value 14
Current Thread Thread -3 var value 15
Current Thread Thread -3 var value 16
Current Thread Thread -3 var value 17
Current Thread Thread -3 var value 18
Error: User Rate Limit Exceeded
272

public class SOP {
    public static void print(String s) {
        System.out.println(s+"\n");
    }
}

public class TestThread extends Thread {
    String name;
    TheDemo theDemo;
    public TestThread(String name,TheDemo theDemo) {
        this.theDemo = theDemo;
        this.name = name;
        start();
    }
    @Override
    public void run() {
        theDemo.test(name);
    }
}

public class TheDemo {
    public synchronized void test(String name) {
        for(int i=0;i<10;i++) {
            SOP.print(name + " :: "+i);
            try{
                Thread.sleep(500);
            } catch (Exception e) {
                SOP.print(e.getMessage());
            }
        }
    }
    public static void main(String[] args) {
        TheDemo theDemo = new TheDemo();
        new TestThread("THREAD 1",theDemo);
        new TestThread("THREAD 2",theDemo);
        new TestThread("THREAD 3",theDemo);
    }
}

synchronizedsynchronized

Output with synchronised

THREAD 1 :: 0
THREAD 1 :: 1
THREAD 1 :: 2
THREAD 1 :: 3
THREAD 1 :: 4
THREAD 1 :: 5
THREAD 1 :: 6
THREAD 1 :: 7
THREAD 1 :: 8
THREAD 1 :: 9
THREAD 3 :: 0
THREAD 3 :: 1
THREAD 3 :: 2
THREAD 3 :: 3
THREAD 3 :: 4
THREAD 3 :: 5
THREAD 3 :: 6
THREAD 3 :: 7
THREAD 3 :: 8
THREAD 3 :: 9
THREAD 2 :: 0
THREAD 2 :: 1
THREAD 2 :: 2
THREAD 2 :: 3
THREAD 2 :: 4
THREAD 2 :: 5
THREAD 2 :: 6
THREAD 2 :: 7
THREAD 2 :: 8
THREAD 2 :: 9

Output without synchronized

THREAD 1 :: 0
THREAD 2 :: 0
THREAD 3 :: 0
THREAD 1 :: 1
THREAD 2 :: 1
THREAD 3 :: 1
THREAD 1 :: 2
THREAD 2 :: 2
THREAD 3 :: 2
THREAD 1 :: 3
THREAD 2 :: 3
THREAD 3 :: 3
THREAD 1 :: 4
THREAD 2 :: 4
THREAD 3 :: 4
THREAD 1 :: 5
THREAD 2 :: 5
THREAD 3 :: 5
THREAD 1 :: 6
THREAD 2 :: 6
THREAD 3 :: 6
THREAD 1 :: 7
THREAD 2 :: 7
THREAD 3 :: 7
THREAD 1 :: 8
THREAD 2 :: 8
THREAD 3 :: 8
THREAD 1 :: 9
THREAD 2 :: 9
THREAD 3 :: 9
Error: User Rate Limit ExceededsynchronizedError: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
8

.

public class SynchronizedCounter {
    private int c = 0;

    public synchronized void increment() {
        c++;
    }

    public synchronized void decrement() {
        c--;
    }

    public synchronized int value() {
        return c;
    }
}

if count is an instance of SynchronizedCounter, then making these methods synchronized has two effects:

First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object. Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.
19

108

synchronizedHashtablesynchronized

non-synchronizedHashMap

2

Object.wait()
6

Synchronized normal methodError: User Rate Limit ExceededSynchronized statementError: User Rate Limit Exceeded

    public synchronized void methodA() {
        // all function code
    }

    equivalent to

    public void methodA() {
        synchronized(this) {
             // all function code
        }
    } 
}

Synchronized static methodError: User Rate Limit ExceededSynchronized statementError: User Rate Limit Exceeded


    public static synchronized void methodA() {
        // all function code
    }

    equivalent to

    public void methodA() {
        synchronized(A.class) {
             // all function code
        }
    } 
}

Error: User Rate Limit Exceeded


    private Object lock1 = new Object();

    public void methodA() {
        synchronized(lock1 ) {
             // all function code
        }
    } 
}

Error: User Rate Limit ExceededsynchronizedError: User Rate Limit ExceededSynchronized MethodsError: User Rate Limit ExceededSynchronized StatementsError: User Rate Limit ExceededSynchronized MethodsError: User Rate Limit ExceededSynchronized StatementsError: User Rate Limit ExceededSynchronized Statements.

Error: User Rate Limit Exceeded

synchronized(object or class) { // object/class use to provides the intrinsic lock
   // code 
}

Error: User Rate Limit Exceededsynchronized

Every object/class have an intrinsic lock associated with it. When a thread invokes a synchronized statement, it automatically acquires the intrinsic lock for that synchronized statement's object and releases it when the method returns. As long as a thread owns an intrinsic lock, NO other thread can acquire the SAME lock => thread safe.

Error: User Rate Limit Exceededthread AError: User Rate Limit Exceededsynchronized(this){// code 1}Error: User Rate Limit Exceededsynchronized(this)Error: User Rate Limit Exceededsynchronized normal methodError: User Rate Limit ExceededSAMEError: User Rate Limit Exceededthread AError: User Rate Limit Exceeded

Error: User Rate Limit Exceededsynchronized(a variable){// code 1}Error: User Rate Limit Exceededsynchronized(class).

SAME LOCKError: User Rate Limit Exceeded

Use synchronized method or synchronized statements?

Error: User Rate Limit Exceededsynchronized statementsError: User Rate Limit Exceededdon't have anyError: User Rate Limit Exceededsynchronized(a variable)).

Error: User Rate Limit Exceededsynchronized methodError: User Rate Limit Exceeded

Note

Error: User Rate Limit ExceededsynchronizedError: User Rate Limit Exceeded

When you use synchronized or normal method or synchronized(this) or synchronized(non-static variable) it will synchronized base on each object instance. When you use synchronized or static method or synchronized(class) or synchronized(static variable) it will synchronized base on class Reference

Error: User Rate Limit Exceeded Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded
814

synchronized

synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods.

In a very, very small nutshell:foosynchronizedfoo

Concurrency Java Memory Model

"Brian Goetz""concurrency"

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
@peterh synchronized делает больше, чем это, следовательно, более подробное объяснение
Error: User Rate Limit Exceeded
Если вы не Брайан Гетц (или, может быть, Джон Скит), почти невозможно получить правильный параллелизм Java только с помощью языковых примитивов (синхронизированных, изменчивых). Для начала используйте пакет java.util.concurrent и постройте его.
6

Error: User Rate Limit Exceeded

4

memory barrierstwo

implicitlyall

Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a ConcurrentLinkedDeque happen-before actions subsequent to the access or removal of that element from the ConcurrentLinkedDeque in another thread.

23

Overview


This can happen directly (by accessing the same variable) or indirectly (by using a class that uses another class that accesses the same variable).

Deeper

synchronizedObjecta lock object{ block of code }.

When execution encounters this keyword, the current thread tries to "lock/acquire/own" (take your pick) the lock object and execute the associated block of code after the lock has been acquired.

Any writes to variables inside the synchronized code block are guaranteed to be visible to every other thread that similarly executes code inside a synchronized code block using the same lock object.

Only one thread at a time can hold the lock, during which time all other threads trying to acquire the same lock object will wait (pause their execution). The lock will be released when execution exits the synchronized code block.

Synchronized methods:

synchronizedlock objectthis (for instance methods)ClassInQuestion.getClass() (for class methods).

- Instance method is a method which does not have static keyword.
- Class method is a method which has static keyword.

Technical


(For example a variable could end up with half of the bits written by one thread and half of the bits written by another thread, leaving the variable in a state that neither of the threads tried to write, but a combined mess of both.)

Conclusion


In other words: Use synchronization, atomic operations or classes that use them for you under the hoods.

Sources

http://docs.oracle.com/javase/specs/jls/se8/html/index.html
Java® Language Specification, 2015-02-13

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
14

Error: User Rate Limit Exceededthread interference and memory consistency errorsError: User Rate Limit Exceeded

Error: User Rate Limit Exceededcritical sectionError: User Rate Limit Exceededcritical section.

When are methods synchronized?

Error: User Rate Limit ExceededsynchronizedError: User Rate Limit Exceeded

What does it mean pro grammatically and logically?

Error: User Rate Limit Exceededcritical sectionError: User Rate Limit Exceededcritical sectionError: User Rate Limit Exceeded

Error: User Rate Limit Exceededcritical section(s)Error: User Rate Limit Exceeded

Error: User Rate Limit ExceededError: User Rate Limit Exceeded

Intrinsic Locks and Synchronization:

Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object's state and establishing happens-before relationships that are essential to visibility.

Every object has an intrinsic lock associated with itError: User Rate Limit Exceeded

Error: User Rate Limit ExceededAs long as a thread owns an intrinsic lock, no other thread can acquire the same lock.Error: User Rate Limit Exceeded

When a thread releases an intrinsic lock, a happens-before relationship is established between that action and any subsequent acquisition of the same lock.

Error: User Rate Limit ExceededError: User Rate Limit Exceeded:

First, it is not possible for two invocations of synchronized methods on the same object to interleave.

Error: User Rate Limit Exceeded

Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object.

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded
76

synchronizedError: User Rate Limit ExceededsynchronizedError: User Rate Limit ExceededsynchronizedError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit ExceededsynchronizedError: User Rate Limit Exceeded

51

synchronized

 if (vector.isEmpty()){
     vector.add(data);
 }

Извините, но у меня есть этот пример и я не понимаю значения: `Integer i1 = Arrays.asList (1,2,3,4,5) .stream (). FindAny (). Get (); synchronized (i1) {Integer i2 = Arrays.asList (6,7,8,9,10) .parallelStream () .sorted () .findAny (). get (); System.out.println (i1 + "+ i2); } `1. Почему вы вызываете блок в первом экземпляре, и этот вызов не влияет на код? 2. Второй экземпляр будет потокобезопасным, несмотря на вызов блока на первом?

Похожие вопросы