对多线程方面一直只限概念,感觉用到的不多,所以没深入去了解。但发现面试时却经常会问到,于是便想了一个简单的题目,亲自实践下。题目如下:
由2个线程控制主线程的一个变量,一个调用加的方法,一个调用减的方法,要求变量值不能小于0(如果等于0,则减的方法必须等待)。一个典型的有货才卖的类型 ,由于新手,所以捣鼓了好久,终于成功了,下面是代码,不知道有什么能改进的。
Java代码:
- public class ThreadTest {
- static Thread1 t1;
- static Thread2 t2;
- /**
- * @param args
- */
- public static void main(String[] args) {
- t2 = new Thread2();
- t1 = new Thread1(t2);
- t1.start();
- t2.start();
- }
- static int num = 0;
- public static void add() {
- num++;
- System.out.println("num+1="+num);
- }
- public synchronized static void minus() {
- if(num <= 0)
- try {
- Thread.currentThread().wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- num--;
- System.out.println("num-1="+num);
- }
- }
- class Thread1 extends Thread {
- Thread2 t2;
- public Thread1(Thread2 t2){
- this.t2 = t2;
- }
- @SuppressWarnings("static-access")
- public void run() {
- int i = 100;
- while(i-->0) {
- // 休息100毫秒,以便更好的检查效果
- /*try {
- this.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }*/
- synchronized (ThreadTest.class) {
- ThreadTest.add();
- }
- if(t2.interrupted())
- notifyAll();
- }
- }
- }
- class Thread2 extends Thread {
- public void notifyer() {
- this.notify();
- }
- public void run() {
- int i = 100;
- while(i>0) {
- synchronized (ThreadTest.class) {
- if(ThreadTest.num>0){
- ThreadTest.minus();
- i--;// 之前把i--写在while里了,老丢数据。
- }
- }
- }
- }
- }
回复1:提个建议,写线程不要直接继承Thread,去实现Runnable,除了更灵活,还能实现资源共享。
回复2:你可以用AtomicLong/AtomicInteger: incrementAndGet()增加数量,在循环中用 get() 和 compareAndSet() 减少数量。 notify就在incrementAndGet以后,wait就在get()返回0以后。
原文参考自:懒人之家www.lanrenzhijia.com 转载请注明