代碼如下:疑問:對于方式一和方式二? 區別就是在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........");? ? }}
對于多線程的開啟的疑問
月亮島Superman
2018-08-03 15:20:26