写两个线程,一个加,一个减

来源:互联网 发布:月薪5000如何理财 知乎 编辑:程序博客网 时间:2024/05/17 06:13

写两个线程,一个加,一个减

package helloworld;import java.util.*;/** * 加一线程与减一线程共同操作一个数 两个问题: 1、线程同步--synchronized 2、线程之间如何共享同一个j变量--内部类 *  * @author liuwei */public class Test {int j = 0;public synchronized void inc() {j++;System.out.println(Thread.currentThread().getName() + "-inc-->" + j);}class T1 implements Runnable {public void run() {inc();}}public synchronized void dec() {j--;System.out.println(Thread.currentThread().getName() + "-dec-->" + j);}class T2 implements Runnable {public void run() {dec();}}public static void main(String[] args) {Test t = new Test();T1 t1 = t.new T1();T2 t2 = t.new T2();for (int i = 0; i < 5; i++) {new Thread(t1).start();new Thread(t2).start();}}}
结果:

Thread-0-inc-->1Thread-1-dec-->0Thread-2-inc-->1Thread-3-dec-->0Thread-5-dec-->-1Thread-6-inc-->0Thread-7-dec-->-1Thread-9-dec-->-2Thread-4-inc-->-1Thread-8-inc-->0



0 0
原创粉丝点击