多线程--设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1
(2014-08-24 14:03:27)
-
-
-
package com.jiaocaigen.test;
-
public class Test {
-
// 采用 Runnable 接口方式创建的多条线程可以共享实例属性
-
-
private int i ;
-
// 同步增加方法
-
-
private synchronized void inc(){
-
i ++;
-
System. out .println(Thread.currentThread().getName()+ "--inc--" + i );
-
}
-
-
// 同步减算方法
-
-
private synchronized void dec(){
-
i --;
-
System. out .println(Thread.currentThread().getName()+ "--dec--" + i );
-
}
-
-
// 增加线程
注意是内部类,且是非静态的
-
class Inc implements Runnable {
-
public void run() {
-
inc();
-
}
-
}
-
-
// 减算线程 注意是内部类,且是非静态的
-
class Dec
extends Thread{
-
public void run() {
-
dec();
-
}
-
}
-
-
public static void main(String[] args) {
-
-
//由于内部类是非静态的,所以这样需要Test的实例化才能调用生成内部类实例
-
Test t = new Test();
-
-
// 内部类的实例化
-
Inc inc = t. new Inc();
//
-
//
Dec dec = t. new Dec();
-
-
Thread thread =
NULL;
-
// 创建 2
个增加线程
-
for ( int i = 0; i < 2; i++) {
-
thread
= new Thread(inc);
//实现Runnable的类的实例化,使用带参数的Thread构造方法.
-
thread.start();
-
}
-
-
// 创建 2
个减少线程
-
for ( int i = 0; i < 2; i++) {
-
thread
= t.new Dec();
//继承Thread的类可以直接实例化.
-
thread.start();
-
}
-
-
}
-
-
}
-
喜欢
0
赠金笔
加载中,请稍候......