JAVA多线程的一段代码

来源:互联网 发布:运营a淘宝需要多少钱 编辑:程序博客网 时间:2024/06/07 09:12

对程序员来说,代码是最直接沟通语言,试看如下代码:

 

public class ThreadTest{
 private int j;
 public static void main(String ars[]){
   ThreadTest1 tt=new ThreadTest1();
  Inc inc=tt.new Inc();
  Dec dec=tt.new Dec();
  for(int i=0;i<2;i++){
    Thread t=new Thread(inc);
   t.start();
   t=new Thread(dec);
   t.start();
   }
 }
 
 private synchronized void inc(){
  j++; System.out.println(Thread.currentThread().getName()+"-inc:"+j);
 }
 
 private synchronized void dec(){
  j--; System.out.println(Thread.currentThread().getName()+"-dec:"+j);
 }
 
 class Inc implements Runnable{
  public void run(){
   for(int i=0;i<100;i++){
     inc();
   }
  }
 }

 class Dec implements Runnable{
  public void run(){
   for(int i=0;i<100;i++){
    dec();
   }
   }
 }
}
使用内部类实现线程,实现四个线程,两个加线程,两个减线程。无序运行。

原创粉丝点击