1

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

那么如果一个对象实现了线程同步,是不是就意味着它是线程安全的呢?

4

2 回答 2

2

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

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

那么如果一个对象实现了线程同步,是不是就意味着[它具有]线程安全呢?

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

于 2013-02-19T04:24:53.410 回答
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 设置为 synchronized 。

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

 * 
 * 
 * */
于 2018-04-24T09:18:14.150 回答