package com.test; public class ThreadTest2 { public static void main(String[] args) { Test1 t=new Test1(); Thread t1=new Thread(t); Thread t2=new Thread(t); t1.start(); t2.start(); } } class Test1 implements Runnable{ int i;//成员变量 @Override public void run() { int i = 0;//局部变量 覆盖掉成员变量 while(true){ System.out.println("i="+i++); if(i==20){ break; } } } } 由于run里 覆盖掉了成员变量,所以两个线程会有自己独立的i变量,两个线程都会打印到19结束。 sleep问题 package com.test; public class ThreadTest3 { public synchronized void hello() throws InterruptedException{ Thread.sleep(5000); System.out.println("hello"); } public synchronized void world(){ System.out.println("world"); } public static void main(String[] args) throws InterruptedException { ThreadTest3 tt = new ThreadTest3(); T1 t1=new T1(tt); t1.start(); Thread.sleep(5000); T2 t2= new T2(tt); t2.start(); } } class T1 extends Thread{ ThreadTest3 tt; public T1(ThreadTest3 tt) { this.tt =tt; } @Override public void run() { try { tt.hello(); } catch (InterruptedException e) { e.printStackTrace(); } } } class T2 extends Thread{ ThreadTest3 tt; public T2(ThreadTest3 tt) { this.tt =tt; } @Override public void run() { tt.world(); } } 永远都是先输出hello后再输出world,sleep不释放锁。 package com.test; public class ThreadTest3 { public synchronized static void hello() throws InterruptedException{ Thread.sleep(5000); System.out.println("hello"); } public synchronized static void world(){ System.out.println("world"); } public static void main(String[] args) throws InterruptedException { ThreadTest3 tt = new ThreadTest3(); T1 t1=new T1(tt); t1.start(); Thread.sleep(5000); ThreadTest3 tt2 = new ThreadTest3(); T2 t2= new T2(tt2); t2.start(); } } class T1 extends Thread{ ThreadTest3 tt; public T1(ThreadTest3 tt) { this.tt =tt; } @Override public void run() { try { tt.hello(); } catch (InterruptedException e) { e.printStackTrace(); } } } class T2 extends Thread{ ThreadTest3 tt; public T2(ThreadTest3 tt) { this.tt =tt; } @Override public void run() { tt.world(); } } static情况,也是先输出hello再输出world
笔记:
关于synchronized关键字的作用
1,在某个对象的所有synchronized方法中,在某一时刻,只能有一个唯一的一个线程去访问这些synchronized方法
2,如果一个synchronized方法,那么该synchronized关键字表示给当前对象上锁(即this)
3,如果一个synchronized方法是静态的(static的)那么该synchronized关键字表示给当前对象锁对于的Class对象上锁。(每个类不管生产多少个对象,其对于的Class对象只有一个)