两个线程轮流打印数字,一直到100
创建一个类,定义两个静态全局变量:
static int num=1;
static Integer in=new Integer(1);
让这个类继承Thread类
重写Thread类里面的run()方法
因为使用两个线程,为了防止数据重复,使用同步synchronized。
@Override
public void run() {
while (true){
synchronized (in){
if (num>100){
System.exit(0);
}else {
System.out.println(num);
num++;
}
}
}
}
创建main()方法
声明两个线程,分别调用start()方法
public static void main(String[] args) {
Demo1 d1=new Demo1();
d1.start();
Demo1 d2=new Demo1();
d2.start();
}
执行结果: