Java线程同步实例

来源:互联网 发布:socket java面试题 编辑:程序博客网 时间:2024/06/06 16:36

Java线程同步实例

package lab8.wu;public class mythread {public static void main(String[] args) {new Create("thread1");new Create("thread2");}}class Create implements Runnable {static int a = 10;private Thread t;public Create(String name) {t = new Thread(this);t.setName(name);t.start();}public void run() {System.out.println("进入同步前"+t.getName()+" "+a);synchronized (this) {Thread t = Thread.currentThread();for (int i = 0; i < 3; i++) {a++;System.out.println(t.getName() + "  " + i+"  a="+a);try {Thread.sleep(1000);} catch (InterruptedException e) {}}}}}

运行结果,thread1和thread2是乱序的,synchronized并未起到作用,synchronized锁住的是两个对象,彼此之间不造成影响: 
thread1和thread2是乱序的,synchronized并未起到作用

对比代码:

package lab8.wu;public class mythread2 {public static void main(String[] args) {Create2 create2=new Create2("th");Thread th1=new Thread(create2,"thread1");Thread th2=new Thread(create2,"thread2");th1.start();th2.start();}}class Create2 implements Runnable {static int a = 10;private Thread t;public Create2(String name) {t = new Thread(this);t.setName(name);t.start();}public void run() {Thread t = Thread.currentThread();System.out.println("进入同步前"+t.getName()+" "+a);synchronized (this) {for (int i = 0; i < 3; i++) {a++;System.out.println(t.getName() + "  " + i+"  a="+a);try {Thread.sleep(1000);} catch (InterruptedException e) {}}}}}

运行结果,synchronized起到作用,在synchronized中的代码同一时间不能被不同的线程同时进入: 
synchronized起到作用

0 0