代码如下,是书上摘下来,挑了一部分,没有全摘下来。问题就是在main方法中一定要这样写吗?可不可以把
"Thread prodT1=new Thread(p1)"这句省略掉。改写为:
Producer p1= new Producer(Stack);
P1.start()请高手解释一下。public class Producer implements Runnable{
private Syncstack thestack;
private int num;
private static int counter=1;
public Producer(syncstack s){
thestack=s;
num = counter++;
}
public void run(){
char c;
for (int i= 0;i<200;i++){
c=(char)(Math.random()*26+'A');
thestack.push(c);
System.out.println("Producer"+num+":"+c);
try{
Thread.sleep(300);
}catch(InterruptedException e){}
}
}
}public class SyncStack{
private Vector buffer = new Vector(400,200);
public synchronized char pop(){
char c;
while(buffer.size() ==0){
try{
this.wait();
}catch(InterruptedException e){}
}
c=((Character)buffer.remove(buffer.size()-1)).charvalue();
return c;
}
public synchronized void push(char c){
this.notif();
Character.charObj= new Character(c);
buffer.addElement(charObj);
}
}public class SnycTest{
public static void main(String args[]){
Syncstack Stack = new Syncstack();
Producer p1= new Producer(Stack);
Thread prodT1 = new Thread(p1);
prodT1.start();
}
}
"Thread prodT1=new Thread(p1)"这句省略掉。改写为:
Producer p1= new Producer(Stack);
P1.start()请高手解释一下。public class Producer implements Runnable{
private Syncstack thestack;
private int num;
private static int counter=1;
public Producer(syncstack s){
thestack=s;
num = counter++;
}
public void run(){
char c;
for (int i= 0;i<200;i++){
c=(char)(Math.random()*26+'A');
thestack.push(c);
System.out.println("Producer"+num+":"+c);
try{
Thread.sleep(300);
}catch(InterruptedException e){}
}
}
}public class SyncStack{
private Vector buffer = new Vector(400,200);
public synchronized char pop(){
char c;
while(buffer.size() ==0){
try{
this.wait();
}catch(InterruptedException e){}
}
c=((Character)buffer.remove(buffer.size()-1)).charvalue();
return c;
}
public synchronized void push(char c){
this.notif();
Character.charObj= new Character(c);
buffer.addElement(charObj);
}
}public class SnycTest{
public static void main(String args[]){
Syncstack Stack = new Syncstack();
Producer p1= new Producer(Stack);
Thread prodT1 = new Thread(p1);
prodT1.start();
}
}
解决方案 »
- myeclipse连接SQLServer数据库出错,因系统中有两个不同版本的SQLServer数据库系统。如何解决
- 对字符串的一点疑问,谢谢
- 各位高手进来帮忙看看这个程序问题在哪?
- eclipse下面打个包放到cvs上,我哭了:-(
- awt中编的一个小窗口如何退出
- 走过路过,不要错过,求一设计思路
- 如何让servlet每天定时运行呢?
- *********这种情况下,我是应该继承还是直接调用?***********
- addTab为什么成为不能解释符号,在线等待,急急急急急
- tomcat默认页
- 请教如何把extend Thread的代码改写成实现了runnable
- 求高手帮我找下这个程序错误在哪里
Producer p1= new Producer(Stack);
P1.start() //会提示没有start方法
其实虽然所有的java书籍上都说实现多线程有两种方式,但是很少有书把这两种方式说清楚。其实准确的说java启动线程只有一种方式,就是利用Thread类启动,至于Runnable只是一个接口而已,如果不借助Thread的话,Runnable是和一个普通接口毫无区别,根本不可能启动线程的。java语言设计Runnable这个接口,并让Thread能够接受Runnable接口的对象,目的只是为了解决java不能支持多重继承的问题。因为有的类可能必须要继承其它的类,可是又必须要实现多线程的操作,这个时候就可能借助Runnable接口来实现。