设计两个线程一个线程做加运算一个线程减运算

来源:互联网 发布:免费2级域名注册永久 编辑:程序博客网 时间:2024/06/06 10:45
package thread;


public class Testthread {


/**
* @param args
* 设计两个线程一个线程做加运算一个线程减运算
* 知识点:1、线程 实现Runnable接口 继承Thread类
* 2、线程的启动start()
* 3、线程安全 同步方法和同步代码块 synchronized
* 4、内部类的创建 Des des=tt.new Des(); 
*/
int j=0;
static Testthread tt=new Testthread();
static Increase inc=tt.new Increase();
static Des des=tt.new Des();
static Thread th1=new Thread(inc);
static Thread th2=new Thread(des);
public static void main(String[] args) {
// TODO Auto-generated method stub
int i=0;



th1.start();
// th1.start();

th2.start();
// th2.start();

         
}

private synchronized void  add(){
for(int i=0;i<100;i++){
j++;
System.out.println(Thread.currentThread().getName()+"加运算"+j);
}}

private synchronized void min(){
for(int i=0;i<100;i++){
j--;
System.out.println(Thread.currentThread().getName()+"减运算"+j);
}
}
class Increase implements Runnable{


@Override
public void run() {

add();
}

}

class Des implements Runnable{


@Override
public void run() {
// TODO Auto-generated method stub
min();
}


}


}
原创粉丝点击