实现多线程
- 继承Thread方法,重写run方法
- 实习Runnable接口,实现run方法
继承Thread和实现Runnable的区别:
- 实现Runnable可以实现代码共享,即同一个代码段可以被多个Thread来启动
-
继承Thread要想实现代码共享,必须在synchronized代码块应用class literal(类名称字面常量),即synchronized(Xxx.class),而synchronized(this)不好使
synchronized用法
- 可以在方法前边加上synchronized修饰符
- 在方法插入synchronized块,
- synchronized(this)
此种方法只能是同一个对象锁,若是new出来的两个对象不会有任何锁限定
- synchronized(Xxx.class)
此种方法对同一个类文件生成的所有对象都会生成锁
继承Thread类如下:
- package thread;
- /**
- * @author zcb zhengchangbai@163.com
- * @date 2011-11-28 上午12:23:49
- */
- public class ExtendsThread extends Thread{
- private static int ticket = 10;
- public ExtendsThread(){
- super();
- }
- public ExtendsThread(String name){
- super(name);
- }
- @Override
- public void run() {
- for (int i = 0; i < 10; i++) {
- //下面是class,所有该class的对象都互斥,而this只对 对象互斥
- synchronized (ExtendsThread.class) {
- ticket--;
- System.out.println(Thread.currentThread().getName()+":"+ticket);
- }
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args) {
- Thread thread = new ExtendsThread("Thread-A");
- Thread thread2 = new ExtendsThread("Thread-B");
- thread.start();
- thread2.start();
- }
- }
实现Runnable接口:
- package thread;
- /**
- * @author zcb zhengchangbai@163.com
- * @date 2011-11-28 上午12:24:56
- */
- public class ImplementRunnable implements Runnable {
- private static int tickets = 10;
- @Override
- public void run() {
- for (int i = 0; i < 10; i++) {
- synchronized (this) {
- tickets--;
- System.out.println(Thread.currentThread().getName()+":"+tickets);
- }
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args) {
- Runnable r = new ImplementRunnable();
- Thread thread = new Thread(r,"Thread-A");
- Thread thread2 = new Thread(r,"Thread-B");
- thread.start();
- thread2.start();
- }
- }
转载于:https://blog.51cto.com/zhengchangbai/727362