两个线程轮流打印数字,一直到100
package com.entity;
public class ThrendTest extends Thread{
private static int num=1;
private static Integer in = new Integer(1);
@Override
public void run() {
while (true) {
if(num<=100){
System.out.println(this.getName()+" "+num++);
}else{
System.exit(0);
}
}
}
}
package com.test;
import com.entity.ThrendTest;
public class MyTest {
public static void main(String[] args) {
ThrendTest test = new ThrendTest();
test.start();
ThrendTest test1 = new ThrendTest();
test1.start();
}
}
第二种方法
package com.hp;
public class MyThrend extends Thread{
private static int num=100;
private Object obj = new Object();
@Override
public void run() {
while (true) {
synchronized (obj){
if(num>0){
try {
System.out.println(this.getName()+"当前线程为"+num--);
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
System.exit(0);
}
}
}
}
}
package com.test;
import com.hp.MyThrend;
public class Main {
//1. 两个线程轮流打印数字,一直到100
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
MyThrend myThrend= new MyThrend();
myThrend.start();
}
}
}