package j2se.threa.syn;
public class Syn {
public static void main(String[] args) {
/*ThreadCase t1 = new ThreadCase(); t1.start(); t1.start();*/ //由于两个都是相同的线程,所以运行一个就可以了,另外一个不能运行,会报错 /* RunnableCase r1 = new RunnableCase(); Thread t1 = new Thread(r1); Thread t2 = new Thread(r1); t1.start(); t2.start();*/ //由于两个线程都是相同的对象,所以执行的是相同的线程 /* ThreadCase2 t1 = new ThreadCase2(); ThreadCase2 t2 = new ThreadCase2(); t1.start(); t2.start();*/ //两个线程由于是不同的对象,所以不能锁住,会同时执行两个线程 /*RunnableCase2 r2 = new RunnableCase2(); Thread t1 = new Thread(r2); Thread t2 = new Thread(r2); t1.start(); t2.start();*/ //由于传进去的对象是同一个对象,所以会有线程锁,只有一个执行玩之后才会执行另一个 }
}
class ThreadCase extends Thread{ public void run(){ try { System.out.println(Thread.currentThread().getId()+"-start"); Thread.sleep(5000); System.out.println(Thread.currentThread().getId()+"-end"); } catch (InterruptedException e) { e.printStackTrace(); } }}
class RunnableCase implements Runnable{ public void run() { try { System.out.println(Thread.currentThread().getId()+"-start"); Thread.sleep(5000); System.out.println(Thread.currentThread().getId()+"-end"); } catch (InterruptedException e) { e.printStackTrace(); } }}
//---------------------同步--------------------------class ThreadCase2 extends Thread{ public void run(){ synchronized(this){ try { System.out.println(Thread.currentThread().getId()+"-start"); Thread.sleep(5000); System.out.println(Thread.currentThread().getId()+"-end"); } catch (InterruptedException e) { e.printStackTrace(); } } }}
class RunnableCase2 implements Runnable{ public void run() { synchronized (this) { try { System.out.println(Thread.currentThread().getId()+"-start"); Thread.sleep(5000); System.out.println(Thread.currentThread().getId()+"-end"); } catch (InterruptedException e) { e.printStackTrace(); } } }}