public class MyThread implements Runnable { private static int total =
10;
@Override public void run() { synchronized (this){ //使用this对象锁 //synchronized (MyThread.class){ //使用MyThread.class类锁
//synchronized (""){//使用字符串锁 System.out.println(Thread.currentThread().getName()
+ "正在运行"); try {
Thread.sleep(100);
} catch (InterruptedException
e) {
e.printStackTrace();
} total--;
System.out.println(total);
System.out.println(Thread.currentThread().getName()
+ "线程结束");
}
}
}
package cn.test;
import cn.myThread.MyThread;
public class TestMyThread { public static void main(String[]
args){ MyThread
myThread = new MyThread();
Thread thread = null; for (int i = 1 ;
i <= 5 ; i++){
thread = new Thread(myThread,"线程"+i);
//开启5个线程,传入同一个对象
thread.start();
}
}
}
public class MyThread implements Runnable { private static int total =
10;
@Override public void run() { synchronized (this){//使用this对象锁 System.out.println(Thread.currentThread().getName()
+ "正在运行"); try {
Thread.sleep(100);
} catch (InterruptedException
e) {
e.printStackTrace();
} total--;
System.out.println(total);
System.out.println(Thread.currentThread().getName()
+ "线程结束");
}
}
}
package cn.test;
import cn.myThread.MyThread;
public class TestMyThread {
public static void main(String[]
args){
Thread thread = null;
for (int i = 1 ; i <= 5 ;
i++){
thread = new Thread(new MyThread(),"线程"+i);//开启5个线程,传入5个不同对象
thread.start();
}
}
}
public class MyThread implements Runnable { private static int total =
10;
@Override public void run() { synchronized (MyThread.class){//使用MyThread.class类锁 System.out.println(Thread.currentThread().getName()
+ "正在运行"); try {
Thread.sleep(100);
} catch (InterruptedException
e) {
e.printStackTrace();
} total--;
System.out.println(total);
System.out.println(Thread.currentThread().getName()
+ "线程结束");
}
}
}
package cn.test;
import cn.myThread.MyThread;
public class TestMyThread { public static void main(String[]
args){
Thread thread = null; for (int i = 1 ;
i <= 5 ; i++){
thread = new Thread(new MyThread(),"线程"+i);
//开启5个线程,传入5个不同对象
thread.start();
}
}
}
public class MyThread implements Runnable { private static int total =
10;
@Override public void run() { synchronized (""){//使用字符串锁
System.out.println(Thread.currentThread().getName()
+ "正在运行"); try {
Thread.sleep(100);
} catch (InterruptedException
e) {
e.printStackTrace();
} total--;
System.out.println(total);
System.out.println(Thread.currentThread().getName()
+ "线程结束");
}
}
}
package cn.test;
import cn.myThread.MyThread;
public class TestMyThread { public static void main(String[]
args){
Thread thread = null; for (int i = 1 ;
i <= 5 ; i++){
thread = new Thread(new MyThread(),"线程"+i);
//开启5个线程,传入5个不同对象
thread.start();
}
}
}