题目
两个线程轮流打印数字,一直到100。
初步实现
class ThreadDemo implements Runnable{
private int i = 1;
public void run() {
while (i<=100) {
try {
Thread.sleep(100);
} catch (Exception e) {
//TODO: handle exception
}
print_number();
}
}
public synchronized void print_number() {
if(i<=100){
System.out.println(Thread.currentThread().getName()+i);
i++;
}
}
}
public class Print_Num{
public static void main(String[] args) {
ThreadDemo threadDemo = new ThreadDemo();
Thread t1 = new Thread(threadDemo, "线程 1 :");
t1.start();
Thread t2 = new Thread(threadDemo, "线程 2 :");
t2.start();
}
}
执行
(base) ➜ test_01 java Print_Num
线程 1 :1
线程 2 :2
线程 2 :3
线程 1 :4
...
...
线程 2 :96
线程 1 :97
线程 2 :98
线程 1 :99
线程 2 :100