详解多线程的两种实现方式以及4个线程,两个线程对j加1,两个线程对j减1完整代码。

//继承Thread方法实现多线程
public class test extends Thread {
public void run()
{
 System.out.println(this.getName());
 }
 public static void main(String[] args)
  {
 System.out.println(Thread.currentThread().getName());
 test thread1 = new test();
 test thread2 = new test ();
 thread1.start();
 thread2.start();
  }

}


//实现Runnable接口方法实现多线程
/*1. 将实现Runnable接口的类实例化。
  2. 建立一个Thread对象,并将第一步实例化后的对象作为参数传入Thread类的构造方法。*/
public class test implements Runnable
{
    public void run()
    {
        System.out.println(Thread.currentThread().getName());
    }
    public static void main(String[] args)
    {
    test t1 = new test();
    test t2 = new test();
    //MyThread1线程名称
        Thread thread1 = new Thread(t1, "MyThread1");
        Thread thread2 = new Thread(t2);
        //定义线程名称为MyThread2
        thread2.setName("MyThread2");
        thread1.start();
        thread2.start();
    }
}

//4个线程,两个线程对j加1,两个线程对j减1
public class test{
private int j;
public static void main(String[] args){
test t = new test();
ADD add = t.new ADD();
SUB sub = t.new SUB();
for(int i=0;i<2;i++){
Thread t1 = new Thread(add);
t1.start();
Thread t2 = new Thread(sub);
t2.start();
}
}
/*这里add方法和sub方法加synchronized关键字是因为当两个线程同时操作同一个变量时,
* 就算是简单的j++操作时,在系统底层也是通过多条机器语句来实现,所以在执行j++过程也是要耗费时间,
* 这时就有可能在执行j++的时候,另外一个线程H就会对j进行操作,因此另外一个线程H可能操作的可能就
* 不是最新的值了。因此要提供线程同步。 
*/
private synchronized void add(){
j++;
System.out.println("1——————"+j);
}
private synchronized void sub(){
j--;
System.out.println("2——————"+j);
}
//加线程
public class ADD implements Runnable{


public void run() {
// TODO Auto-generated method stub
for(int i=0;i<1000;i++){
add();
}
}
}
//减线程
public class SUB implements Runnable{


public void run() {
// TODO Auto-generated method stub
for(int i=0;i<1000;i++){
sub();
}

}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值