設計4個線程,其中兩個線程每次對j增加1,另外兩個線程對j每次減少1。


public class ThreadTest {

private int j = 1;

//+1
private synchronized void n(){
j++;
System.out.println(Thread.currentThread().getName()+"n:"+j);
}

//-1
private synchronized void m(){
j--;
System.out.println(Thread.currentThread().getName()+"m:"+j);
}

//加線程
private class N implements Runnable{
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 10; i++) {
n();
}
}
}

//減線程
private class M implements Runnable{
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 10; i++) {
m();
}
}
}

public static void main(String[] args) {
ThreadTest tt = new ThreadTest();
//創建2個線程類
Thread t = null;
N n = tt.new N();
M m = tt.new M();
//啟動4個線程
for (int i = 0; i <2; i++) {
t=new Thread(n);
t.start();
t=new Thread(m);
t.start();
}
}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM