本帖最后由 NNERO 于 2014-4-26 14:56 编辑
- public class Text111
- {
- public static void main(String[] args)
- {
- Res r1 = new Res("nero",18);
- Ras r2 = new Ras("nnnnnero","man");
- Thread t1 = new Thread(r1);
-
-
- t1.start();
-
- r2.start();
- }
- }
- class Res implements Runnable{
- String name;
- int age;
- int count = 100;
- boolean flag = true;
-
- public Res(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- public void run(){
- while(true){
- synchronized(Res.class){
- try {
- if(!flag)
- Res.class.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- if(count>0){
- count--;
- System.out.println(Thread.currentThread().getName()+"..."+name+"..."+age+"..."+count);
- flag=true;
- }
- Res.class.notify();
- }
- }
- }
- }
- class Ras extends Thread{
- String name;
- String sex;
- int count=100;
- boolean flag = true;
-
- public Ras(String name, String sex) {
- super();
- this.name = name;
- this.sex = sex;
- }
- public void run(){
- while(true){
- synchronized(Ras.class){
- if(flag)
- try {
- Res.class.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- if(count>0){
- System.out.println(name+"::"+sex);
- count--;
- flag = false;
- }
- Res.class.notify();
- }
- }
- }
- }
复制代码 我用了2种方法创建了2个线程,想让它们交替打印,但是运行出错啊。
我知道2个线程的wait方法必须用同一个锁,但是我这里Res.class这个其实也是同一个对象啊,直接调用它的wait方法应该可以啊
不知道什么地方出问题了。。 求解答!!!
|