當前位置:編程學習大全網 - 編程軟體 - 用JAVA寫壹個多線程程序,如寫四個線程,二個對壹個變量減壹,輸出。

用JAVA寫壹個多線程程序,如寫四個線程,二個對壹個變量減壹,輸出。

public class ThreadTest1{

private int j;

public static void main(String args[]){

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();

}

}

}

}

  • 上一篇:linux操作系統基礎教程第二版課後答案linux操作系統基礎教程
  • 下一篇:matlab編程中怎樣求壹個矩陣的特征值和特征向量?
  • copyright 2024編程學習大全網