六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 36|回复: 0

多线程修改单一变量值

[复制链接]

升级  8.67%

15

主题

15

主题

15

主题

秀才

Rank: 2

积分
63
 楼主| 发表于 2013-1-26 13:03:59 | 显示全部楼层 |阅读模式
 
package org.fanzone.thread;
 
/** 
 * Title: base<br> 
 * Description: Thread Handler<br> 
 * Copyright: Copyright (c) 2011 <br> 
 * Create DateTime: Jun 14, 2011 3:06:51 PM <br> 
 * @author wangmeng
 */
public class ThreadHandle {
 
/**global variable*/
private int count;

public static void main(String[] args){

ThreadHandle th = new ThreadHandle();

/**the initials of the two inner classes*/
ThreadOne to = th.new ThreadOne();
ThreadTwo tt = th.new ThreadTwo();

Thread t = new Thread(to);
t.start();
t.setName("p");
t = new Thread(tt);
t.start();
t.setName("m");
}

/**
* synchronized method to superimposite 
*/
private synchronized void plus(){
count++;
System.out.println(Thread.currentThread().getName()+" -- "+count);
}

/**
* synchronized method to descend
*/
private synchronized void minus(){
count--;
System.out.println(Thread.currentThread().getName()+" -- "+count);
}

/**
* Title: base<br> 
* Description: A inner class which deal with the plus handler<br> 
* Copyright: Copyright (c) 2011 <br> 
* Create DateTime: Jun 14, 2011 3:09:40 PM <br> 
* @author wangmeng
*/ 
class ThreadOne implements Runnable{
public void run(){
for(int i=0;i<100;i++){
plus();
}
}
}

/**
* Title: base<br> 
* Description: A inner class which deal with the minus handler<br> 
* Copyright: Copyright (c) 2011 <br> 
* Create DateTime: Jun 14, 2011 3:09:40 PM <br> 
* @author wangmeng
*/ 
class ThreadTwo implements Runnable{
public void run(){
for(int i=0;i<100;i++){
minus();
}
}
}
}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表