为了帮助你在有效的时间内提高考试成绩,我们考吧网整理了有关计算机等级二级考试复习资料和方法技巧,希望通过本次练习对你有所帮助。
2013年计算机二级Java多线程入门技巧和方法5
使用Synchronized关键字同步类方法
要想解决"脏数据"的问题,最简单的方法就是使用synchronized关键字来使run方法同步,代码如下public synchronized void run()
2.{
3.
4.}
从上面的代码可以看出,只要在void和public之间加上synchronized关键字,就可以使run方法同步,也就是说,对于同一个Java类的对象实例,run方法同时只能被一个线程调用,并当前的run执行完后,才能被其他的线程调用。即使当前线程执行到了run方法中的yield方法,也只是暂停了一下。由于其他线程无法执行run方法,因此,最终还是会由当前的线程来继续执行。先看看下面的代码:
sychronized关键字只和一个对象实例绑定
5.class Test
6.{
7. public synchronized void method()
8. {
9.
10. }
11.}
12.
13.public class Sync implements Runnable
14.{
15. private Test test;
16. public void run()
17. {
18. test.method();
19. }
20. public Sync(Test test)
21. {
22. this.test = test;
23. }
24. public static void main(String[] args) throws Exception
25. {
26. Test test1 = new Test();
27. Test test2 = new Test();
28. Sync sync1 = new Sync(test1);
29. Sync sync2 = new Sync(test2);
30. new Thread(sync1)。start();
31. new Thread(sync2)。start();
32. }
33. }
在Test类中的method方法是同步的。但上面的代码建立了两个Test类的实例,因此,test1和test2的method方法是分别执行的。要想让method同步,必须在建立Sync类的实例时向它的构造方法中传入同一个Test类的实例,如下面的代码所示:
Sync sync1 = new Sync(test1); 不仅可以使用synchronized来同步非静态方法,也可以使用synchronized来同步静态方法。如可以按如下方式来定义method方法:
34.class Test
35.{
36. public static synchronized void method() { }
37.}
建立Test类的对象实例如下:
38.Test test = new Test();
对于静态方法来说,只要加上了synchronized关键字,这个方法就是同步的,无论是使用test.method(),还是使用Test.method()来调用method方法,method都是同步的,并不存在非静态方法的多个实例的问题。
在23种设计模式中的单件(Singleton)模式如果按传统的方法设计,也是线程不安全的,下面的代码是一个线程不安全的单件模式。
39.package test;
40.
41.// 线程安全的Singleton模式
42.class Singleton
43.{
44. private static Singleton sample;
45.
46. private Singleton()
47. {
48. }
49. public s static Singleton getInstance()
50. {
51. if (sample == null)
52. {
53. Thread.yield(); // 为了放大Singleton模式的线程不安全性
54. sample = new Singleton();
55. }
56. return sample;
57. }
58.}
59.public class MyThread extends Thread
60.{
61. public void run()
62. {
63. Singleton singleton = Singleton.getInstance();
64. System.out.println(singleton.hashCode());
65. }
66. public static void main(String[] args)
67. {
68. Thread threads[] = new Thread;
69. for (int i = 0; i < threads.length; i++)
70. threads[i] = new MyThread();
71. for (int i = 0; i < threads.length; i++)
72. threads[i].start();
73. }
74.}
在上面的代码调用yield方法是为了使单件模式的线程不安全性表现出来,如果将这行去掉,上面的实现仍然是线程不安全的,只是出现的可能性小得多。
程序的运行结果如下:
25358555
26399554
7051261
29855319
5383406
上面的运行结果可能在不同的运行环境上有所有同,但一般这五行输出不会完全相同。从这个输出结果可以看出,通过getInstance方法得到的对象实例是五个,而不是我们期望的一个。这是因为当一个线程执行了Thread.yield()后,就将CPU资源交给了另外一个线程。由于在线程之间切换时并未执行到创建Singleton对象实例的语句,因此,这几个线程都通过了if判断,所以,就会产生了建立五个对象实例的情况(可能创建的是四个或三个对象实例,这取决于有多少个线程在创建Singleton对象之前通过了if判断,每次运行时可能结果会不一样)。
要想使上面的单件模式变成线程安全的,只要为getInstance加上synchronized关键字即可。代码如下
75.public static synchronized Singleton getInstance() { }
当然,还有更简单的方法,就是在定义Singleton变量时就建立Singleton对象,代码如下
76.private static final Singleton sample = new Singleton();
然后在getInstance方法中直接将sample返回即可。这种方式虽然简单,但不知在getInstance方法中创建Singleton对象灵活。读者可以根据具体的需求选择使用不同的方法来实现单件模式。
编辑推荐: