本帖最后由 skill20 于 2014-4-23 19:13 编辑
- public class LockTest
- {
- public static void main(String[] args)
- {
- Thread t1 = new Thread(new InterPut());
- Thread t2 = new Thread(new OutPut());
- t1.start();
- t2.start();
- }
- }
- class InterPut implements Runnable
- {
- Person a = Person.getS();
- boolean f;
- public void run()
- {
- int x = 0;
- while(true)
- {
- if(x == 0)
- a.set("zhangya_________",23);
- else
- a.set("chenghu——————————————",26);
- x = (x + 1)%2;
- }
- }
- }
- class OutPut implements Runnable
- {
- Person b = Person.getS();
- public void run()
- {
- while(true)
- {
- b.get();
- }
- }
- }
- class Person
- {
- private static boolean flag;
- private static String name;
- private static int age;
- private static Person s = new Person("lishi",45);
- private Person(String name, int age)
- {
- s.name = name;
- s.age = age;
- }
- public static Person getS()
- {
- return s;
- }
- public synchronized void set(String name , int age)
- {
- if(flag == true)
- try{ s.wait();}
- catch(Exception e){}
- s.name = name;
- s.age = age;
- flag = true;
- s.notify();
- }
- public synchronized void get()
- {
- if(flag == false)
- try{ s.wait();}
- catch (Exception e){}
- System.out.println(s.name + s.age);
- flag = false;
- s.notify();
- }
- }
复制代码
|