问题以:1
一程序有A 和B两线程
当A 线程运行到一半时 被SLEEP()
B运行,然后A又运行
这时候A是重新开始 还是接着完成剩下的代码? 问题以:2
这段代码编译时,电脑滴响了一阵子,把类的名字改了 为Conn又OK了
为什么啊?
class Con implements Runnable
{
Q q;
public Con(Q q)
{
this.q=q;
}
public void run()
{
while(true)
{
System.out.print(q.name);
}
}
}
一程序有A 和B两线程
当A 线程运行到一半时 被SLEEP()
B运行,然后A又运行
这时候A是重新开始 还是接着完成剩下的代码? 问题以:2
这段代码编译时,电脑滴响了一阵子,把类的名字改了 为Conn又OK了
为什么啊?
class Con implements Runnable
{
Q q;
public Con(Q q)
{
this.q=q;
}
public void run()
{
while(true)
{
System.out.print(q.name);
}
}
}
还有一个问题 3:
class test2
{
public static void main(String [] args)
{
Q q = new Q();
Pro p = new Pro(q);
cons c = new cons(q);
Thread tp = new Thread(p);
Thread tc = new Thread(p);
tp.setDaemon(true);
tc.setDaemon(true);
tp.start();
tc.start();
System.out.println("main11111");
}
}
这个是生产者和消费者的运行主类,如果是写成下面这样,就无限循环,但如上面所写
就打印了main11111了而已,就不运行了,为什么啊,应该是tp 和tc线程变成了后台线程
先运行一下,才停止啊 ????
new Thread(new Pro(q)).start();
new Thread(new cons(q)).start();
tc.setDaemon(true);改成false才行
cons c = new cons(q);//cons的代码贴出来?
class Pro implements Runnable
{
Q q;
public Pro(Q q)
{
this.q=q;
}
public void run()
{
int i=0;
while(true)
{
if(i==0)
q.put("AAA----","----aaa");
else
q.put("BBB++++","++++bbb");
i=(i+1)%2;
}
}
}class cons implements Runnable
{
Q q;
public cons(Q q)
{
this.q=q;
}
public void run()
{
while(true)
{
q.get();
}
}
}class Q
{
String name="unknown";
String sex = "unknown";
boolean bFull = false;
public synchronized void put(String name,String sex)
{
if(bFull)
try{wait();}catch(Exception e){}
this.name = name;
try{Thread.sleep(1);}catch(Exception e){}
this.sex = sex;
bFull=true;
notify();
}
public synchronized void get()
{
if(!bFull)
try{wait();}catch(Exception e){}
System.out.print(name);
System.out.println(""+sex);
bFull=false;
notify();
}
}
class test2
{
public static void main(String [] args)
{
Q q = new Q();
new Thread(new Pro(q)).start();
new Thread(new cons(q)).start();
}
}
就打印了main11111了而已,就不运行了,为什么啊,应该是tp 和tc线程变成了后台线程
先运行一下,才停止啊 ????
-------------------------------------
我运行了你的代码,不会停止阿,一直在跑阿
class test2
{
public static void main(String [] args)
{
Q q = new Q();
new Thread(new Pro(q)).start();
new Thread(new cons(q)).start();
}
}
是不会停止阿,一直在跑但如果主类写出这样:
class test2
{
public static void main(String [] args)
{
Q q = new Q(); Pro p = new Pro(q);
cons c = new cons(q);
Thread tp = new Thread(p);
Thread tc = new Thread(p);
tp.setDaemon(true);
tc.setDaemon(true);
tp.start();
tc.start();
System.out.println("main11111");
}
}
就打印了main11111了而已,就不运行了。
为什么啊,应该是tp 和tc线程变成了后台线程
先运行一下,才停止啊 ????
像你原来的程序都是由一个runnable 产生的,只是在put当然不会有结果输出。