黑马程序员技术交流社区
标题:
设计4个线程,其中两个线程每次对j增加1,另外两个线程...
[打印本页]
作者:
莫泊桑leon
时间:
2014-9-10 12:20
标题:
设计4个线程,其中两个线程每次对j增加1,另外两个线程...
public class TestThread3{
private int j;
public static void main(String[] args){
TestThread3 t = new TestThread3();
Inc inc = t.new Inc();
Dec dec = t.new Dec();
for(int i=0;i<2;i++){
Thread ts = new Thread(inc);
ts.start();
ts= new Thread(dec);
ts.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<10;i++){
inc();
}
}
}
class Dec implements Runnable{
public void run(){
for(int i=0;i<10;i++){
dec();
}
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2