本帖最后由 王少雷 于 2013-1-22 22:31 编辑
public class ThreadTest4 {
/**
* 定义四个线程,2个线程对J++,2个线程对J--
*/
private static int j = 0;(这里这与写)
private int j = 0;这么写有区别么。
还有 下面dec 和 inc 不加synchronized呢~~~
public static void main(String[] args) {
Thread t;
Inc inc = new ThreadTest4().new Inc();
Dec dec = new ThreadTest4().new Dec();
for(int i=0; i<2; i++)
{
t = new Thread(inc);
t.start();
t = new Thread(dec);
t.start();
}
}
public synchronized void inc()
{
j++;
System.out.println(Thread.currentThread().getName()+"---inc:"+j);
}
public synchronized void dec()
{
j--;
System.out.println(Thread.currentThread().getName()+"---dec:"+j);
}
class Inc implements Runnable
{
public void run() {
for(int i=0; i<100; i++)
{
new ThreadTest4().inc();
}
}
}
class Dec implements Runnable
{
public void run() {
for(int i=0; i<100; i++)
{
new ThreadTest4().dec();
}
}
}
}
我们来积极讨论一下啊。。。 |