你应该让你的执行线程停顿一下,一边别的线程又执行的可能。
例如:
class myThreadone implements Runnable
{
public void run()
{
for(int i=0;i<100;i++){
System.out.println(""+i);
try{
sleep(20); //20ms
}
catch(Exception e){
}
}
}
}
例如:
class myThreadone implements Runnable
{
public void run()
{
for(int i=0;i<100;i++){
System.out.println(""+i);
try{
sleep(20); //20ms
}
catch(Exception e){
}
}
}
}
{
public void run()
{
for(int i=0;i<100;i++){
System.out.println(""+i);
try{
yield(); //20ms
}
catch(Exception e){
}
}
}
}
{
public void run()
{
for(int i=0;i<100;i++){
System.out.println(""+i);
try{
Thread.yield(); }
catch(Exception e){
}
}
}
}
sleep()与yield()皆是Thread的类方法,
怎么可以在实现Runnable接口的类中直接用呢.要想实现
0
100
1
101
2
102
.
.
.
98
198
99
199
的效果,你要
class myThreadone implements Runnable
{
public void run()
{
for(int i=0;i<100;i++)
{
System.out.println(""+i);
try{
Thread. yield();
}
catch(Exception e){} }
}
}class myThreadtwo implements Runnable
{
public void run()
{
for(int i=100;i<200;i++)
{
System.out.println(i);
try{
Thread. yield();
}
catch(Exception e){}
}
}
}
public void run(){
try{
for(int i=0;i<10;i++){
Thread.sleep(1000);
System.out.println("ThreadM");
}
}
catch(InterruptedException ex){
ex.printStackTrace();
}
}
}
虽然不是一个一个的交错,但是确实能体现线程在cpu队列里排队的性质
Thread thread1=new Thread(new myThreadone());
Thread thread2=new Thread(new myThreadtwo());
thread1.start();
thread2.start();
}
}
class myThreadone implements Runnable
{
public void run()
{
for(int i=0;i<100;i++)
{
try{
System.out.println(""+i);
Thread.yield();
}catch(Exception e){e.printStackTrace();}
}
}
}
class myThreadtwo implements Runnable
{
public void run()
{
for(int i=100;i<200;i++)
{
try{
System.out.println(i);
Thread.yield();
}catch(Exception e){e.printStackTrace();}
}
}
}
不用信号量了,你的线程不多,略微改动一下就可实现你需要的要求
Thread thread2=new Thread(new myThreadtwo());
thread1.start();
thread2.start();
}
}
class myThreadone implements Runnable
{
public void run()
{
for(int i=0;i<100;i++){
System.out.println("" + i);
Thread.yield();
}
}
}
class myThreadtwo implements Runnable
{
public void run()
{
for(int i=100;i<200;i++){
System.out.println(i);
Thread.yield() ;
}
}
}