请大神帮我写个实例,要的效果是:写两个线程,交替打印数字和字母。
谢谢
谢谢
解决方案 »
- SWT browser
- thinking in java 4中的疑问,请高手帮帮忙?感谢!!
- 新手,请问为什么有时候要不停的new ,有时候用引用就可以了??
- 送分题!!!!!!!!!!!!!!!!!!!!!快!!!!!!!抢分啊!!!!!!!!!
- 达人请进!新手在线等!MyEclipse+jsp初级问题。。。。。。。
- Windows XP下Java程序退出锁资源管理器???
- 散分-自勉--6-17日结贴(5)
- 请问timeStamp方法怎么转换为时间类型
- 简单的程序就是通不过?
- 请教Java Swing 搜狗输入法的问题
- 请教怎样从文件读到的内容一行行分析
- 怎样用Java调用Linux的cp命令?
// TODO Auto-generated method stub
ExecutorService service = Executors.newFixedThreadPool(2);
service.execute(new Runnable() { @Override
public void run() {
// TODO Auto-generated method stub
int i = 0;
for (; i < 26; i++) {
System.out.println(i);
Thread.yield();
}
}
});
service.execute(new Runnable() {
char[] cs = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z' }; @Override
public void run() {
// TODO Auto-generated method stub
int i = 0;
for (; i < 26; i++) {
System.out.println(cs[i]);
Thread.yield();
}
}
}); }
{
public static void main(String[] args)
{
Out o=new Out(); //用于线程同步.
AlphaOut an=new AlphaOut(o); //输出字母,'a'--'z'循环输出。
NumberOut num=new NumberOut(o); //输出数字,1--100循环输出。
new Thread(an).start();
new Thread(num).start();
}
}
class AlphaOut implements Runnable
{
private Out o;
char c='z';
public AlphaOut(Out o)
{
this.o = o;
}
public void run()
{
while(true)
{
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
synchronized(o)
{
while(o.getFlag())
{
try
{
o.wait();
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
c=c>='z'?'a':(char)(c+1);
System.out.println("Alpaha out "+c);
o.setFlag(true);
o.notifyAll();
}
}
}
}class NumberOut implements Runnable
{
private Out o;
int x=0;
public NumberOut(Out o)
{
this.o = o;
}
public void run()
{
while(true)
{
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
synchronized(o)
{
while(!o.getFlag())
{
try
{
o.wait();
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
x=x>=100?1:x+1;
System.out.println("Number out "+x);
o.setFlag(false);
o.notifyAll();
}
}
}
}
class Out
{
private boolean flag=false;
public void setFlag(boolean flag)
{
this.flag=flag;
}
public boolean getFlag()
{
return flag;
}
}