第一次入学面试线程题。那时没捣鼓出来。好悲伤。。两个线程交替打印1-10的数字。。
线程类:
public class PrintNumRunnable implements Runnable {
int num = 1 ;
@Override
public synchronized void run() {
{
while (num <11){
System.out.println( Thread.currentThread().getName() +":"+num );
num ++ ;
this.notifyAll();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
主类
public class TreadPrintOneToTen {
public static void main(String[] args) {
PrintNumRunnable printlnNum = new PrintNumRunnable();
Thread t1 = new Thread (printlnNum);
t1.setName("t1");
Thread t2 = new Thread (printlnNum);
t2.setName("t2");
t1.start();
t2.start();
}
}
发帖的原因是有问题还没弄懂。。
线程中的int num = 1。。为何t1线程和t2线程都共享这个数据?第一次做的时候还比较保守的弄了个构造函数来方便设值
int num ;
public PrintNumRunnable(int num ){
this .num = num ;
}
static修饰修饰变量。共享变量。。那块也比较模糊。。觉得static int num= 0更好点。。
线程同步那学得晕晕的。。这题是不是应该用啥锁啥的。。期待有人用锁机制解决这问题。求代码。。
没用心学。有错勿喷。。 |
|