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 }
  • 相关阅读:
    Java学习:冒泡排序和选择排序
    Java学习:多态
    Java学习:抽象类与接口
    Java学习:继承
    Java学习:标准类
    Java学习:方法简介
    传参的本质
    new 关键字做的事
    一个引用类型的对象占多大堆空间
    栈中空间大小
  • 原文地址:https://www.cnblogs.com/chlde/p/2743708.html
Copyright © 2011-2022 走看看