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

时间:2013-02-19 03:32:09

标签: multithreading synchronization thread-safety

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

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

2 个答案:

答案 0 :(得分:2)

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

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

  

因此,如果一个对象实现了线程同步,那么它是否意味着   [它有]线程安全吗?

如果同步正确,是的。如果你不小心的话,很容易做错(或不完全),在这种情况下,即使是同步程序,由于缺乏线程安全性,程序可能偶尔会崩溃或输出错误。

答案 1 :(得分:0)

是。线程同步意味着线程安全。如果有2张门票,那里有3个顾客。然后,如果我必须声明一个方法来随机选择哪些线程将获得票证必须是一个同步的方法。请看一下这个很容易理解的例子。

        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

 */

如果我们使用Executors.newSingleThreadExecutor(),则不需要同步。这里我没有将方法m1设为同步。

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

 * 
 * 
 * */