WINDOWS环境下,线程是分配时间片调度运行的。
试想,在一个时间片内,只有Producer在运行,此时运行到SLEEP时,正好Q的NAME是ROSE,而SEX是MALE,这时线程要SLEEP了。WINDOWS则调度到下一个线程,即Consumer线程运行,打印的结果是ROSE----MALE。
Producer的SLEEP结束,线程调度到Producer运行了,和上次一样,运行到SLEEP的时候,再次调度到Consumer。
所以结果就只能是ROSE----MALE。
试想,在一个时间片内,只有Producer在运行,此时运行到SLEEP时,正好Q的NAME是ROSE,而SEX是MALE,这时线程要SLEEP了。WINDOWS则调度到下一个线程,即Consumer线程运行,打印的结果是ROSE----MALE。
Producer的SLEEP结束,线程调度到Producer运行了,和上次一样,运行到SLEEP的时候,再次调度到Consumer。
所以结果就只能是ROSE----MALE。
自己想为什么
{
Q q=null;
public Producer(Q q)
{
this.q=q;
}
public void run()
{
int i=0;
while(true)
{
System.out.println("Thread:Producer");
//synchronized(q){
if(i==0)
{
System.out.println("Thread:Producer:0");
q.name="John"; q.sex="male";
}
else
{
System.out.println("Thread:Producer:else");
q.name="Rose";
//try{Thread.sleep(1000);}
//catch(Exception e){System.out.println(e.getMessage());}
q.sex="female";
}
try
{
Thread.sleep(1000);
}
catch(Exception e)
{ }
i=(i+1)%2;//}
}
}
}
改成這樣就可以了.
public TestThread() {
} public static void main(String[] args) {
Q q = new Q();
new Thread(new Producer(q)).start();
new Thread(new Consumer(q)).start();
}}class Producer
implements Runnable {
Q q = null;
public Producer(Q q) {
this.q = q;
} public void run() {
int i = 0;
while (true) {
//synchronized(q){
if (i%2 == 0) {
q.name = "John";
q.sex = "male";
}
else {
q.name = "Rose";
q.sex = "female"; }
// q.notifyAll();
try {
Thread.sleep(1000);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
i ++; //}
}
}
}class Q {
String name = "Rose";
String sex = "female";
}class Consumer
implements Runnable {
Q q = null;
public Consumer(Q q) {
this.q = q;
} public void run() {
while (true) {
//synchronized(q){
System.out.println(q.name + "------------>" + q.sex);
try {
Thread.sleep(100);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
//}
}
}
}