主题:Java 多线程的一个程序错在哪?
大家帮我看看我这个程序到底哪里有问题。我刚刚学习Java,大家多多支持。先谢谢大家了。
很简单的一个Producer和Customer得问题利用多线程。
package ProCus;
import java.util.*;
class ProCus
{
public static void main(String [] args)
{
Sta t=new Sta();
Consumer a1=new Consumer(t);
Consumer a2=new Consumer(t);
Pro s=new Pro(t,"producer1");
s.start();
try
{
Thread.sleep(100);
}
catch(Exception e)
{
e.printStackTrace();
}
a1.start();
a2.start();
}
}
class Pro extends Thread
{
private Sta t;
String name;
Pro(Sta t,String name)
{
this.name=name;
t=this.t;
}
public void run()
{
t.Push(name);
System.out.println("Producer: "+name);
}
}
class Consumer extends Thread
{
private Sta p;
String name;
Consumer(Sta p)
{
this.p=p;
}
public void run()
{
while(!p.Empty())
{
name=(String)p.Pop();
System.out.println("Consumer:"+name);
try
{
Thread.sleep(100);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
class Sta
{
private LinkedList a=new LinkedList();
synchronized boolean Empty()
{
return a.isEmpty();
}
synchronized void Push(Object o)
{
a.addFirst(o);
}
synchronized Object Pop()
{
if(!a.isEmpty())
{
return a.removeFirst();
}
else
{
return "null";
}
}
}
很简单的一个Producer和Customer得问题利用多线程。
package ProCus;
import java.util.*;
class ProCus
{
public static void main(String [] args)
{
Sta t=new Sta();
Consumer a1=new Consumer(t);
Consumer a2=new Consumer(t);
Pro s=new Pro(t,"producer1");
s.start();
try
{
Thread.sleep(100);
}
catch(Exception e)
{
e.printStackTrace();
}
a1.start();
a2.start();
}
}
class Pro extends Thread
{
private Sta t;
String name;
Pro(Sta t,String name)
{
this.name=name;
t=this.t;
}
public void run()
{
t.Push(name);
System.out.println("Producer: "+name);
}
}
class Consumer extends Thread
{
private Sta p;
String name;
Consumer(Sta p)
{
this.p=p;
}
public void run()
{
while(!p.Empty())
{
name=(String)p.Pop();
System.out.println("Consumer:"+name);
try
{
Thread.sleep(100);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
class Sta
{
private LinkedList a=new LinkedList();
synchronized boolean Empty()
{
return a.isEmpty();
}
synchronized void Push(Object o)
{
a.addFirst(o);
}
synchronized Object Pop()
{
if(!a.isEmpty())
{
return a.removeFirst();
}
else
{
return "null";
}
}
}