java: Thread 和 runnable线程类

java: Thread 和 runnable线程类

Java有2种实现线程的方法:Thread类,Runnable接口。(其实Thread本身就是Runnable的子类)

Thread类,默认有run(), start()方法,继承Thread类,需要实现run方法

Thread多线程,不能共享资源,保证数据的的统一(以商城商品数量,售票系统票的数量为例)

例如:

public class MyThread extends Thread {
	private String name; // 定义name属性

	public MyThread(String name) {
		this.name = name;
	}

	public void run() {// 覆写run()方法
		for (int i = 0; i < 50; i++) {// 表示循环10次
			System.out.println("Thread运行:" + name + ",i = " + i);
		}
	}
}

实现1:

 此种方法说明:mt1线程执行完后,才能执行mt2线程

public class ThreadDemo01 {
	public static void main(String[] args) {
		MyThread mt1 = new MyThread("线程A") ;
		MyThread mt2 = new MyThread("线程B") ;
		mt1.run() ;	// 调用线程体
		mt2.run() ;	// 调用线程体
	}
}

  

 

实现2:

start()方法表示,调用系统底层方法,去抢占cpu资源,谁先抢到,谁就能优先得到cpu的调度

public class ThreadDemo02 {
	public static void main(String[] args) {
		MyThread mt1 = new MyThread("线程A");
		MyThread mt2 = new MyThread("线程B");
		mt1.start(); // 调用线程体
		mt2.start(); // 调用线程体

	}

}

  

 

 

 

 

Runnable:

public class MyThread implements Runnable { // 实现Runnable接口
	private String name; // 定义name属性

	public MyThread(String name) {
		this.name = name;
	}

	public void run() {// 覆写run()方法
		for (int i = 0; i < 50; i++) {// 表示循环10次
			System.out.println("Thread运行:" + name + ",i = " + i);
		}
	}
}

  

实现子类:

public class RunnableDemo01 {
	public static void main(String[] args) {
		MyThread mt1 = new MyThread("线程A");
		MyThread mt2 = new MyThread("线程B");
		new Thread(mt1).start(); // 调用线程体
		new Thread(mt2).start(); // 调用线程体
	}
}

  

 

推荐实现Runnable接口来使用多线程。

使用Runnable能实现资源共享,以商城/售票系统为例,售卖票

Thread例子:

public class MyThread extends Thread {// 继承Thread类
	private int ticket = 5; // 一共才5张票

	public void run() {// 覆写run()方法
		for (int i = 0; i < 50; i++) {// 表示循环10次
			if (this.ticket > 0) {
				System.out.println("卖票:ticket = " + this.ticket--);
			}
		}
	}
}

  

实现子类:

此种方法:其实票一共只有5张,但是三个线程,每个线程都能买到5张票,这样是不符合逻辑的

public class ThreadTicket {
	public static void main(String[] args) {
		MyThread mt1 = new MyThread(); // 一个线程
		MyThread mt2 = new MyThread(); // 一个线程
		MyThread mt3 = new MyThread(); // 一个线程
		mt1.start() ;	// 开始卖票
		mt2.start() ;	// 开始卖票
		mt3.start() ;	// 开始卖票
	}

}

  

 

实现方法二:

public class MyThread implements Runnable {// 实现Runnable接口
	private int ticket = 5; // 一共才5张票

	public void run() {// 覆写run()方法
		for (int i = 0; i < 50; i++) {// 表示循环10次
			if (this.ticket > 0) {
				System.out.println("卖票:ticket = " + this.ticket--);
			}
		}
	}
}

  

实现子类:

此方法,能实现线程内的资源共享,不会卖出多余的票

public static void main(String[] args) {
		MyThread mt = new MyThread(); // 一个对象
		new Thread(mt).start() ;// 一个线程开始卖票
		new Thread(mt).start() ;//一个线程
new Thread(mt).start() ; // 一个线程开始卖票
}
}

  

 

 

posted @ 2016-12-02 21:46  穆晟铭  阅读(300)  评论(0编辑  收藏  举报