50,543
社区成员
发帖
与我相关
我的任务
分享
package testone;
public class print {
private boolean flag=true;//为真打印数字,为假打印字母
public print() {
}
public synchronized void printNumber(String s)
{
try
{
if(!flag)
{
wait();
}
else//为真时进入
{
System.out.print(s);
flag=false;
notifyAll();
}
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
public synchronized void printLetter(String s)
{
try
{
if(flag)
{
wait();
}
else//为假时进入
{
System.out.print(s);
flag=true;
notifyAll();
}
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
}
package testone;
public class numthread extends Thread{
public print printer;
public numthread(String name,print printer) {
super(name);
this.printer=printer;
// TODO Auto-generated constructor stub
}
public void run()
{
for(int i=1;i<=51;i+=2)
{
String s=i+""+(i+1);
printer.printNumber(s);
}
}
}
package testone;
public class letterthread extends Thread {
public print printer;
public letterthread(String name,print printer) {
super(name);
this.printer=printer;
// TODO Auto-generated constructor stub
}
public void run()
{
for(int i=1;i<=26;i+=1)
{
int temp=i+64;
char c=(char) temp;
printer.printLetter(c+"");
}
}
}
package testone;
public class printTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
print printer=new print();
new numthread("打印数字线程",printer).start();;
new letterthread("打印字母线程",printer).start();
}
}
public synchronized void printNumber(String s)
{
try
{
if(!flag)
{
wait();
}
else//为真时进入
{
System.out.print(s);
flag=false;
notifyAll();
}
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
就拿这段来说,比如传3的时候wait(),你觉得线程唤醒之后走什么?不可能去走else的package test;
public class print {
private boolean flag=true;//为真打印数字,为假打印字母
public print() {
}
public synchronized void printNumber(String s)
{
try
{
if(!flag)
{
wait();
}
System.out.print(s);
flag=false;
notifyAll();
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
public synchronized void printLetter(String s)
{
try
{
if(flag)
{
wait();
}
System.out.print(s);
flag=true;
notifyAll();
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
}
把线程中的else去掉,再测试就可以了。