- class Res
- {
- public String name;
- public String sex;
- }
- class Input implements Runnable
- {
- private Res r;
- Input(Res r)
- {
- this.r = r;
- }
- public void run()
- {
- int x = 0;
- while(true)
- {
- synchronized(r)
- {
- if (x == 0)
- {
- r.name = "mike";
- r.sex = "man";
- }
- else
- {
- r.name = "林青霞";
- r.sex = "女女女";
- }
- x = ++x % 2;
- }
- }
- }
- }
- class Output implements Runnable
- {
- private Res r;
- Output(Res r)
- {
- this.r = r;
- }
- public void run()
- {
- synchronized(r)
- {
- System.out.println(r.name + "-------" + r.sex);
- }
- }
- }
- class Test
- {
- public static void main(String[] args)
- {
- Res r = new Res();
- Input in = new Input(r);
- Output out = new Output(r);
- Thread t1 = new Thread(in);
- Thread t2 = new Thread(out);
- t1.start();
- t2.start();
- }
- }
复制代码
|
|