小弟刚学java,有关线程的这一段总是有错误,我找不到,请大家帮忙,谢谢class Q
{
private String name="陈琼";
private String sex="女";
public synchronized void put(String name,String sex)
{
this.name=name;
try
{
Thread.sleep(10);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
this.sex=sex;
}
public synchronized void get()
{
System.out.println(name+"-----"+sex);
}
}
class Producer implements Runnable
{
Q q=null;
public Producer(Q q)
{
this.q=q;
}
public void run()
{
while(true)
{
int i=0;
if(i==0)
{
q.put("陈琼","女");
}
else
{
q.put("张小林","男");
}
i=(i+1)%2;
}
}
}
class Consumer implements Runnable
{
Q q=null;
public Consumer(Q q)
{
this.q=q;
}
public void run()
{
while(true)
{
q.get();
}
}
}
public class ThreadCommunation
{
Q q=new Q(); new Thread(new Producer(q)).start();
new Thread(new Consumer(q)).start();
}------------------------------
new Thread(new Producer(q)).start();
new Thread(new Consumer(q)).start();
就是这2句有问题,请大家帮忙看下,谢谢先
{
private String name="陈琼";
private String sex="女";
public synchronized void put(String name,String sex)
{
this.name=name;
try
{
Thread.sleep(10);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
this.sex=sex;
}
public synchronized void get()
{
System.out.println(name+"-----"+sex);
}
}
class Producer implements Runnable
{
Q q=null;
public Producer(Q q)
{
this.q=q;
}
public void run()
{
while(true)
{
int i=0;
if(i==0)
{
q.put("陈琼","女");
}
else
{
q.put("张小林","男");
}
i=(i+1)%2;
}
}
}
class Consumer implements Runnable
{
Q q=null;
public Consumer(Q q)
{
this.q=q;
}
public void run()
{
while(true)
{
q.get();
}
}
}
public class ThreadCommunation
{
Q q=new Q(); new Thread(new Producer(q)).start();
new Thread(new Consumer(q)).start();
}------------------------------
new Thread(new Producer(q)).start();
new Thread(new Consumer(q)).start();
就是这2句有问题,请大家帮忙看下,谢谢先
{
private String name="陈琼";
private String sex="女";
public synchronized void put(String name,String sex)
{
this.name=name;
try
{
Thread.sleep(10);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
this.sex=sex;
}
public synchronized void get()
{
System.out.println(name+"-----"+sex);
}
}
class Producer implements Runnable
{
Q q=null;
public Producer(Q q)
{
this.q=q;
}
public void run()
{
while(true)
{
int i=0;
if(i==0)
{
q.put("陈琼","女");
}
else
{
q.put("张小林","男");
}
i=(i+1)%2;
}
}
}
class Consumer implements Runnable
{
Q q=null;
public Consumer(Q q)
{
this.q=q;
}
public void run()
{
while(true)
{
q.get();
}
}
}
public class ThreadCommunation
{
public static void main(String args[]){
Q q=new Q();
new Thread(new Producer(q)).start();
new Thread(new Consumer(q)).start();
}
}
hello,lz你没写main函数吧?