zoukankan      html  css  js  c++  java
  • 四个线程,对一个变量进行+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 }
  • 相关阅读:
    webpack学习1-打包
    Cordova开发-2 自定义插件
    Vue项目开发1-项目的创建
    Cordova开发-2 具体插件的使用
    Cordova开发-1 项目的创建
    Mybatis的使用
    XAMPP设置上的问题
    七款Debug工具推荐:iOS
    sqlite内置函数
    CATransition常用动画及type
  • 原文地址:https://www.cnblogs.com/chlde/p/2743708.html
Copyright © 2011-2022 走看看