四个线程,对一个变量进行+1,-1。用Thread和Runnable实现

 1 public class Mtest {
 2 
 3     int j;
 4     
 5     public synchronized void inc(){
 6         j++;
 7         System.out.println("plus j is:"+j+"/t thread is:"+Thread.currentThread().getName());
 8     }
 9     
10     public synchronized void dec(){
11         j--;
12         System.out.println("menurs j is:"+j+"/t thread is:"+Thread.currentThread().getName());
13     }
14     
15     class thread1 implements Runnable{
16         
17         @Override
18         public void run() {
19 
20             while (true) {
21 
22                 inc();
23                 try {
24                     Thread.sleep(1000);
25                 } catch (InterruptedException e) {
26                     // TODO Auto-generated catch block
27                     e.printStackTrace();
28                 }
29             }
30             
31         }
32         
33     }
34     
35     class thead2 extends Thread{
36 
37         @Override
38         public void run() {
39 
40             while (true) {
41 
42                 dec();
43                 try {
44                     Thread.sleep(1000);
45                 } catch (InterruptedException e) {
46                     // TODO Auto-generated catch block
47                     e.printStackTrace();
48                 }
49             }
50         }
51         
52     }
53     /**
54      * @param args
55      */
56     public static void main(String[] args) {
57 
58         Mtest t = new Mtest(); 
59         thread1 t1 = t.new thread1();
60         for (int i = 0; i < 2; i++) {
61             Thread kk = new Thread(t1);
62             Thread tt = t.new thead2();
63             kk.start();
64             tt.start();
65         }
66     }
67 
68 }

转载于:https://www.cnblogs.com/chlde/archive/2012/10/28/2743708.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值