62,628
社区成员
发帖
与我相关
我的任务
分享
public class myThread implements Runnable {
public void run() {
int i = 100;
while(true){
System.out.println(Thread.currentThread().getName() + ":" + i);
i--;
Thread.yield();
if (i<0) {
break;
}
}
}
}
public class test {
public static void main(String[] args) {
myThread mt = new myThread();
Thread t1 = new Thread(mt);
Thread t2 = new Thread(mt);
t1.setName("线程1");
t2.setName("线程2");
t1.start();
t2.start();
}
}
class myThread implements Runnable {
public void run() {
while(i > 0){
synchronized(this){
currentThreadName = Thread.currentThread().getName();
if(currentThreadName.equals(threadName)){
continue;
}
System.out.println(currentThreadName + ":" + i --);
threadName = currentThreadName;
}
}
}
private int i = 100;
private String threadName = null;
private String currentThreadName = null;
}
public class Test {
public static void main(String[] args) {
myThread mt = new myThread();
Thread t1 = new Thread(mt);
Thread t2 = new Thread(mt);
t1.setName("线程1");
t2.setName("线程2");
t1.start();
t2.start();
}
}