Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Multithreading 线程同步是否意味着线程安全?_Multithreading_Synchronization_Thread Safety - Fatal编程技术网

Multithreading 线程同步是否意味着线程安全?

Multithreading 线程同步是否意味着线程安全?,multithreading,synchronization,thread-safety,Multithreading,Synchronization,Thread Safety,严格定义的线程同步或序列化是特定机制的应用,以确保两个并发执行的线程或进程不会同时执行程序的特定部分。(摘自维基百科) 因此,如果对象实现线程同步,是否意味着它是线程安全的?线程同步是实现线程安全的一种方法。线程安全仅仅意味着一个程序可以同时运行多个线程,而不会有任何可能破坏彼此的状态 但是,在某些情况下,在没有线程同步的情况下,线程安全是可能的——例如,如果两个线程都从同一数据结构中读取数据,但没有线程修改数据结构,那么该程序可以是线程安全的,而不需要任何线程同步。还有一些无锁数据结构,设计为

严格定义的线程同步或序列化是特定机制的应用,以确保两个并发执行的线程或进程不会同时执行程序的特定部分。(摘自维基百科)


因此,如果对象实现线程同步,是否意味着它是线程安全的?

线程同步是实现线程安全的一种方法。线程安全仅仅意味着一个程序可以同时运行多个线程,而不会有任何可能破坏彼此的状态

但是,在某些情况下,在没有线程同步的情况下,线程安全是可能的——例如,如果两个线程都从同一数据结构中读取数据,但没有线程修改数据结构,那么该程序可以是线程安全的,而不需要任何线程同步。还有一些无锁数据结构,设计为可由多个线程使用,无需同步

那么,如果一个对象实现线程同步,这是否意味着 [它有]线程安全性


如果同步操作正确,则为“是”。如果不小心,很容易出错(或不完全),在这种情况下,即使进行了同步,由于缺乏线程安全性,程序仍可能偶尔崩溃或给出错误的输出。

是的。线程同步意味着线程安全。如果有两张票和三位顾客。然后,如果我必须声明一个随机选择哪些线程将获得票证的方法,那么它必须是一个同步方法。请看一看这个非常容易理解的示例

        public class ThreadSynchronization {
            public static void main(String[] args) {
                Ticketbooking tb = new Ticketbooking();
                Thread t1 = new Thread(tb);
                Thread t2 = new Thread(tb);
                Thread t3 = new Thread(tb);
                t1.start();
                t2.start();
                t3.start();
            }

        }

        class Ticketbooking implements Runnable {
            int tickets = 3;

            @Override
            public void run() {
                System.out.println("waiting => " + Thread.currentThread().getName());
                m1();

            }

            private synchronized void m1() {
                if (tickets > 0) {
                    System.out.println("booking for => " + Thread.currentThread().getName());
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    tickets--;
                    System.out.println("Booked for => " + Thread.currentThread().getName());
                    System.out.println("tickets now => " + tickets);

                } // if
                else {
                    System.out.println("ticket not booked for => " + Thread.currentThread().getName());
                } // else

            }
        }// end1 
    /*
    The output will be :
    waiting => Thread-0
    waiting => Thread-1
    waiting => Thread-2
    booking for => Thread-0
    Booked for => Thread-0
    tickets now => 1
    booking for => Thread-2
    Booked for => Thread-2
    tickets now => 0
    ticket not booked for => Thread-1
*/
也可以使用Executors.newFixedThreadPool()解决此问题。以下是解决方案:

public class Test13 {
    public static void main(String[] args) {
        Ticketbooking1 tb1 = new Ticketbooking1();

        ExecutorService service = Executors.newFixedThreadPool(3);

        for (int i = 0; i < 3; i++) {
            service.execute(tb1);
        }
        service.shutdown();

    }
}

class Ticketbooking1 implements Runnable {
    int tickets = 2;

    @Override
    public void run() {
        System.out.println("waiting => " + Thread.currentThread().getName());
        m1();

    }

    private synchronized void m1() {
        if (tickets > 0) {
            System.out.println("booking for => " + Thread.currentThread().getName());
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            tickets--;
            System.out.println("Booked for => " + Thread.currentThread().getName());
            System.out.println("tickets now => " + tickets);

        } // if
        else {
            System.out.println("ticket not booked for => " + Thread.currentThread().getName());
        } // else
    }

}// end1

/*  The output :
 * waiting => pool-1-thread-1
waiting => pool-1-thread-3
waiting => pool-1-thread-2
booking for => pool-1-thread-1
Booked for => pool-1-thread-1
tickets now => 1
booking for => pool-1-thread-2
Booked for => pool-1-thread-2
tickets now => 0
ticket not booked for => pool-1-thread-3

 */
public class Test13 {
    public static void main(String[] args) {
        Ticketbooking1 tb1 = new Ticketbooking1();

        ExecutorService service = Executors.newSingleThreadExecutor();
        service.execute(tb1);
        service.execute(tb1);
        service.execute(tb1);
        service.shutdown();

    }
}

class Ticketbooking1 implements Runnable {
    int tickets = 2;

    @Override
    public void run() {
        System.out.println("waiting => " + Thread.currentThread().getName());
        m1();

    }

    private void m1() {
        if (tickets > 0) {
            System.out.println("booking for => " + Thread.currentThread().getName());
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            tickets--;
            System.out.println("Booked for => " + Thread.currentThread().getName());
            System.out.println("tickets now => " + tickets);

        } // if
        else {
            System.out.println("ticket not booked for => " + Thread.currentThread().getName());
        } // else
    }

}// end1

/*  the output :
 * waiting => pool-1-thread-1
booking for => pool-1-thread-1
Booked for => pool-1-thread-1
tickets now => 1
waiting => pool-1-thread-1
booking for => pool-1-thread-1
Booked for => pool-1-thread-1
tickets now => 0
waiting => pool-1-thread-1
ticket not booked for => pool-1-thread-1

 * 
 * 
 * */