- import javax.management.loading.PrivateClassLoader;
- import java.util.*;
- public class A{
- public static void main(String[] args) {
- Resource r=new Resource ();
- new Thread(new In( r)).start();
- new Thread(new Out(r)).start();
- }
- }
- class Resource {
- String name;
- String sex;
-
- }
- class In implements Runnable{
- private Resource r;
- Object obj =new Object();
- In( Resource r) {
- this.r=r;
- }
-
- public void run(){
- int x=0;
- while (true) {synchronized (obj) {
-
-
- if (x==0) {
- r.name="lilili";
- r.sex="fimel";
-
- } else {
-
- r.name="丽丽";
- r.sex="女女女女女";
- }
- x=(x+1)%2;
- }
- }
- }
- }
- class Out implements Runnable{
- private Resource r;
- Object obj=new Object();
- Out( Resource r) {
- this.r=r;
- }
- public void run(){
- while(true){
- synchronized (obj) {
- System.out.print(r.name+"----");
- System.out.println(r.sex);
- }
- }
- }
复制代码 输出结果如下:
丽丽----女女女女女
lilili----fimel
丽丽----女女女女女
lilili----女女女女女
丽丽----fimel
lilili----fimel
lilili----女女女女女
lilili----女女女女女
lilili----fimel
lilili----fimel
lilili----女女女女女
丽丽----女女女女女
lilili----女女女女女
lilili----fimel
lilili----女女女女女
丽丽----女女女女女
丽丽----女女女女女
lilili----女女女女女
丽丽----fimel
丽丽----女女女女女
lilili----fimel
丽丽----女女女女女
丽丽----fimel
|