1、理解程序、进程、线程的概念
程序可以理解为静态的代码
进程可以理解为执行中的程序
线程可以理解为进程的进一步细分,程序的一条执行路径
使用多线程的优点:
- 提高应用程序的响应。对图形化界面更有意义,可增强用户体验。
- 提高计算机系统CPU的利用率
- 改善程序结构。将既长又复杂的进程分为多个线程,独立运行,利于理解和修改
Thread的常用方法:
1、start( ):启动线程并执行相应的run()方法
2、run( ):子线程要执行的代码放入run()方法中
3、currentThread( ):静态的,调取当前的线程
4、getName( ):获取此线程的名字
5、setName( ):设置线程的名字
6、yield( ):调用此方法多线程释放当前CPU的执行权
7、在A线程中调用B线程的join()方法,表示:当执行到此方法,A线程停止执行,直至B线程执行完毕,A线程再接着join()之后的代码执行
8、isAlive( ) :判断当前线程是否还存活
9、sleep(long l): 显示的让当前线程睡眠1毫秒
10、线程通信:wait() notify() notifyAll()
设置线程的优先级
getPriority():返回线程的优先级值
setPriority(int newPriority):改变线程的优先级
2、如何创建java程序的线程
方式一:继承于Thread类
class PrintNum extends Thread{
public PrintNum(String name){
super(name);
}
public void run(){
//子线程执行的代码
for(int i = 1;i <= 100;i++){
if(i % 2 == 0){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
public class TestThread {
public static void main(String[] args) {
PrintNum p1 = new PrintNum("线程1");
PrintNum p2 = new PrintNum("线程2");
p1.setPriority(Thread.MAX_PRIORITY);//10
p2.setPriority(Thread.MIN_PRIORITY);//1
p1.start();//要想启动一个多线程,必须调用start方法,不能用run方法
p2.start();
}
}
//模拟火车站售票窗口,开启三个窗口售票,总票数为100张
//存在线程的安全问题
class Window extends Thread {
static int ticket = 100;//要将全局变量声明为静态,不然每个对象都有这个属性,会卖出300张票
public void run() {
while (true) {
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "售票,票号为:"+ ticket--);
} else {
break;
}
}
}
}
public class TestWindow {
public static void main(String[] args) {
Window w1 = new Window();
Window w2 = new Window();
Window w3 = new Window();
w1.setName("窗口1");
w2.setName("窗口2");
w3.setName("窗口3");
w1.start();
w2.start();
w3.start();
}
}
创建多线程的方式二:通过实现Runnable接口的方式
//1.创建一个实现了Runnable接口的类
class PrintNum1 implements Runnable {
//2.实现接口的抽象方法
public void run() {
// 子线程执行的代码
for (int i = 1; i <= 100; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
public class TestThread1 {
public static void main(String[] args) {
//3.创建一个Runnable接口实现类的对象
PrintNum1 p = new PrintNum1();
//要想启动一个多线程,必须调用start()
//4.将此对象作为形参传递给Thread类的构造器中,创建Thread类的对象,此对象即为一个线程
Thread t1 = new Thread(p);
//5.调用start()方法:启动线程并执行run()
t1.start();//启动线程
//再创建一个线程
Thread t2 = new Thread(p);
t2.start();
}
}
对比一下继承的方式 vs 实现的方式
- 1.联系:public class Thread implements Runnable(继承的方式的Thread也实现了Runnable接口)
- 2.哪个方式好?
实现的方式优于继承的方式 why?
① 避免了java单继承的局限性
② 如果多个线程要操作同一份资源(或数据),更适合使用实现的方式
3、线程的生命周期
1、线程安全问题存在的原因:
由于一个线程在操作共享数据过程中,未执行完毕的情况下,另外的线程参与进来,导致共享数据存在了安全问题。
2、如何解决线程安全问题
必须让一个线程操作共享数据完毕以后,其它线程才有机会参与共享数据的操作。
3、java如何实现线程安全:线程的同步机制
- 方式一:同步代码块
synchronized(同步监视器){
//需要被同步的代码块(即为操作共享数据的代码)
}
1、共享数据:多个线程共同操作的同一个数据(变量)
2、同步监视器:由任何一个类的对象来充当。哪个线程获取此监视器,谁就执行大括号里被同步的代码。俗称:锁
注:在实现的方式中,考虑同步的话,可以使用this来充当锁。但是在继承的方式中,慎用this
class Window2 implements Runnable {
int ticket = 100;// 共享数据
// Object obj = new Object();
public void run() {
// Animal a = new Animal();//局部变量
while (true) {
synchronized (this) {//this表示当前对象,本题中即为w
if (ticket > 0) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "售票,票号为:" + ticket--);
}
}
}
}
}
public class TestWindow2 {
public static void main(String[] args) {
Window2 w = new Window2();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
class Animal{
}
- 方式二:同步方法
将操作共享数据的方法声明为synchronized. 即此方法为同步方法,能够保证当其中一个线程执行此方法时,其他线程在外等待直至此线程执行完此方法。》同步方法的锁:this(不用显式的写)
class Window4 implements Runnable {
int ticket = 100;// 共享数据
public void run() {
while (true) {
show();
}
}
public synchronized void show() {
if (ticket > 0) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "售票,票号为:"
+ ticket--);
}
}
}
public class TestWindow4 {
public static void main(String[] args) {
Window4 w = new Window4();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
//关于懒汉式的线程安全问题:使用同步机制
//对于一般的方法内,使用同步代码块,可以考虑使用this。
//对于静态方法而言,使用当前类本身充当锁。
class Singleton {
private Singleton() {
}
private static Singleton instance = null;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {//对于静态方法而言,使用当前类本身充当锁。
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
public class TestSingleton {
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2);
// Class clazz = Singleton.class;
}
}
同步的局限性:导致程序的执行效率要降低
同步方法(非静态的)的锁为this。
同步方法(静态的)的锁为当前类本身。
例:
银行有一个账户。有两个储户分别向同一个账户存3000元,每次存1000,存3次。每次存完打印账户余额。
class Account{
double balance;//余额
public Account(){
}
//存钱
public synchronized void deposit(double amt){
notify();
balance+=amt;
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":"+balance);
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Customer extends Thread{
Account account;
public Customer(Account account){
this.account=account;
}
public void run(){
for(int i=0;i<3;i++){
account.deposit(1000);
}
}
}
public class TestAccount {
public static void main(String[] args) {
Account acct = new Account();
Customer c1 = new Customer(acct);
Customer c2 = new Customer(acct);
c1.setName("甲");
c2.setName("乙");
c1.start();
c2.start();
}
}
小结:
释放锁的操作
当前线程的同步方法、同步代码块执行结束
当前线程在同步代码块、同步方法中遇到break、return终止了该代码块、该方法的继续执行。
当前线程在同步代码块、同步方法中出现了未处理的Error或Exception,导致异常结束
当前线程在同步代码块、同步方法中执行了线程对象的wait()方法,当前线程暂停,并释放锁。
不会释放锁的操作
线程执行同步代码块或同步方法时,程序调用Thread.sleep()、Thread.yield()方法暂停当前线程的执行
线程执行同步代码块时,其他线程调用了该线程的suspend()方法将该线程挂起,该线程不会释放锁(同步监视器)。
应尽量避免使用suspend()和resume()来控制线程
4、线程的死锁问题
死锁:不同的线程分别占用对方需要的同步资源不放弃,都在等待对方放弃自己需要的同步资源,就形成了线程的死锁
解决方法:专门的算法、原则;尽量减少同步资源的定义
//死锁的问题:处理线程同步时容易出现。
//不同的线程分别占用对方需要的同步资源不放弃,都在等待对方放弃自己需要的同步资源,就形成了线程的死锁
//写代码时,要避免死锁!
public class TestDeadLock {
static StringBuffer sb1 = new StringBuffer();
static StringBuffer sb2 = new StringBuffer();
public static void main(String[] args) {
new Thread() {
public void run() {
synchronized (sb1) {
try {
Thread.currentThread().sleep(10);//问题放大
} catch (InterruptedException e) {
e.printStackTrace();
}
sb1.append("A");
synchronized (sb2) {
sb2.append("B");
System.out.println(sb1);
System.out.println(sb2);
}
}
}
}.start();
new Thread() {
public void run() {
synchronized (sb2) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
sb1.append("C");
synchronized (sb1) {
sb2.append("D");
System.out.println(sb1);
System.out.println(sb2);
}
}
}
}.start();
}
}
5、线程通信
wait() 与 notify() 和 notifyAll()
- wait():令当前线程挂起并放弃CPU、同步资源,使别的线程可访问并修改共享资源,而当前线程排队等候再次对资源的访问
- notify():唤醒正在排队等待同步资源的线程中优先级最高者结束等待
- notifyAll ():唤醒正在排队等待资源的所有线程结束等待.
Java.lang.Object提供的这三个方法只有在synchronized方法或synchronized代码块中才能使用,否则会报java.lang.IllegalMonitorStateException异常
//例:使用两个线程打印 1-100. 线程1, 线程2 交替打印
class PrintNum implements Runnable{
int num=1;
public void run(){
while (true){
synchronized (this) {
notify();
if(num<=100){
try {
Thread.currentThread().sleep(10);//放大问题
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":"+num);
num++;
}else {
break;
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class TestCommunication {
public static void main(String[] args){
PrintNum p=new PrintNum();
Thread t1=new Thread(p);
Thread t2=new Thread(p);
t1.setName("甲");
t2.setName("乙");
t1.start();
t2.start();
}
}
经典例题:生产者/消费者问题
生产者(Productor)将产品交给店员(Clerk),而消费者(Customer)从店员处取走产品,店员一次只能持有固定数量的产品(比如:20),如果生产者试图生产更多的产品,店员会叫生产者停一下,如果店中有空位放产品了再通知生产者继续生产;如果店中没有产品了,店员会告诉消费者等一下,如果店中有产品了再通知消费者来取走产品。
分析:
1、是否涉及到多线程的问题?是!生产者、消费者
2、是否涉及到共享数据?有!考虑线程安全问题
3、此共享数据是谁?产品的数量
4、是否涉及到线程的通信呢?存在生产者与消费者的通信
class Clerk{//店员
int product;
public synchronized void addProduct(){//生产产品
if(product >= 20){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
product++;
System.out.println(Thread.currentThread().getName() + ":生产了第" + product + "个产品");
notifyAll();
}
}
public synchronized void consumeProduct(){//消费产品
if(product <= 0){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
System.out.println(Thread.currentThread().getName() + ":消费了第" + product + "个产品");
product--;
notifyAll();
}
}
}
class Producer implements Runnable{//生产者
Clerk clerk;
public Producer(Clerk clerk){
this.clerk = clerk;
}
public void run(){
System.out.println("生产者开始生产产品");
while(true){
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
clerk.addProduct();
}
}
}
class Consumer implements Runnable{//消费者
Clerk clerk;
public Consumer(Clerk clerk){
this.clerk = clerk;
}
public void run(){
System.out.println("消费者消费产品");
while(true){
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
clerk.consumeProduct();
}
}
}
public class TestProduceConsume {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Producer p1 = new Producer(clerk);
Consumer c1 = new Consumer(clerk);
Thread t1 = new Thread(p1);//一个生产者的线程
Thread t3 = new Thread(p1);
Thread t2 = new Thread(c1);//一个消费者的线程
t1.setName("生产者1");
t2.setName("消费者1");
t3.setName("生产者2");
t1.start();
t2.start();
t3.start();
}
}