线程的同步
先看线程不同步的情况:
//数据类 package com.itjob; public class Person { private String name = "王非"; private String sex = "女"; public void put(String name, String sex) { this.name = name; this.sex = sex; } public void get() { System.out.println(name + "----->" + sex); } } //用来显示Person数据 package com.itjob; public class Consumer implements Runnable { Person person; public Consumer(Person person) { this.person = person; } public void run() { while(true) { person.get(); } } } //用来修改Person数据 package com.itjob; public class Producer implements Runnable { Person person; public Producer(Person person) { this.person = person; } public void run() { int i = 0; while(true) { if(i==0) { person.put("刘祥", "男"); }else{ person.put("王非", "女"); } i = (i+1)%2; } } } //主程序类 package com.itjob; public class ThreadCom { public static void main(String[] args) { Person person = new Person(); new Thread(new Producer(person)).start(); new Thread(new Consumer(person)).start(); } }
运行的结果如图:
修改为线程同步
只需要修改Person类就OK了,同步只是对数据加锁,与线程无关,当多个线程访问同一个数据的时候,就要对数据加锁(同步)
修改后的代码如:
//数据类 package com.itjob; public class Person { private String name = "王非"; private String sex = "女"; public synchronized void put(String name, String sex) { this.name = name; this.sex = sex; } public synchronized void get() { System.out.println(name + "----->" + sex); } }
运行的结果不会有男女不分的情况!
http://www.5itjob.com
http://www.rjpx.net