threadexp3two.java

来自「java关于多线程的课堂练习」· Java 代码 · 共 59 行

JAVA
59
字号
/**
 * @(#)ThreadExp3Two.java
 *
 *
 * @author 
 * @version 1.00 2007/12/3
 */
public class ThreadExp3Two {
        
    /**
     * Creates a new instance of <code>ThreadExp3</code>.
     */
    public ThreadExp3Two() {
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
       Thread threadA,threadB;
       TargetObject  a=new TargetObject();
       threadA=new Thread(a);
       threadB=new Thread(a);
      
       threadA.setName("add1");
       threadB.setName("sub1");
       
       threadA.start();
       threadB.start();
       
    }
}
class  TargetObject  implements  Runnable {
 
 
 public void run() {
  int  number=0;
  while (true) {
   if (Thread.currentThread().getName().substring(0,3).equals("add")) {
     number++;
     System.out.println("现在是"+Thread.currentThread().getName()+"在运行 number等于"+number);
   }
   if (Thread.currentThread().getName().substring(0,3).equals("sub")) {
   	number--;
   	System.out.println("现在是"+Thread.currentThread().getName()+"在运行 number等于"+number);
   }
   try {
    Thread.sleep(1000);
   }
   catch (InterruptedException e) {
     System.out.println("there is interruption!"+e);
   }
  }
 }
 
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?