ITPub博客

首页 > IT职业 > > 对于多线程的开启的疑问

对于多线程的开启的疑问

作者:cdfoxman 时间:2019-04-12 18:04:12 0 删除 编辑

代码如下:

疑问:对于方式一和方式二  区别就是在new Thread()时候,方式一是传递了同一个 Processor对象p,而方式二是new了两个Processor对象,请问单独从这点来说 对于后续 启动两个线程有什么不同之处吗?


即使new Thread是传递同一个Processor对象p  t1.start() 和 t2.start() 都会开启两个线程。

而这种方式 也是 会开启两个线程  这两种方式有什么区别吗???

 Thread t1 = new Thread(new Processor());

 Thread t2 = new Thread(new Processor());




public class synchronized {

    public static void main(String[] args) throws InterruptedException {

//方式一

MyClass m = new MyClass();

Processor p = new Processsor(m);

Thread t1 = new Thread(p);

Thread t2 = new Thread(p);

 t1.start();

 t2.start();

//方式二-----------------------------------------------------------------

        Thread t1 = new Thread(new Processor());

        Thread t2 = new Thread(new Processor());

        t1.start();

        t2.start();

    }

}


class Processsor implements Runnable {


MyClass mc;

public Processor() {}

public Processor(MyClass mc) {

this.mc  =  mc;

}


    @Override

    public void run() {

        if ("t1".equals(Thread.currentThread().getName())) {

            MyClass02.m1();   //类锁

        }

        if ("t2".equals(Thread.currentThread().getName())) {

            MyClass02.m2();

        }

    }

}



class MyClass {

    public synchronized static void m1() {

        try {

            Thread.sleep(5000);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        System.out.println("m1........");

    }


  

    public synchronized static void m2() {

        System.out.println("m2........");

    }

}


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/625/viewspace-3153886/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-12

  • 博文量
    237
  • 访问量
    1739