多线程
创建多线程
jvm允许创建多线程
java.lang.Thread
1.继承Thread类,子类重写Thread的run方法,调Thread额start方法
package com.myselfProject.ThreadDemo;
public class ziThread extends Thread {
@Override
public void run() {
for (int i = 0; i <100 ; i++) {
if(i %2 ==0){
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+i);
}
}
}
public ziThread(String name){
super(name);
}
public static void main(String[] args) {
//主线程命名
Thread.currentThread().setName("主线程");
ziThread ziThread = new ziThread("子线程");
//ziThread.setName("lx");
ziThread.start();
System.out.println("hello");
for (int i = 0; i <100 ; i++) {
if(i %2 ==0){
System.out.println(Thread.currentThread().getName()+i+"*");
}
}
new Thread(){
@Override
public void run() {
for (int i = 0; i <100 ; i++) {
if(i %2 !=0){
System.out.println(i);
}
}
}
}.start();
}
}
常用方法
start()线程开启
run()线程要实现的逻辑
currentThread()返回当前代码执行的线程
getName()获取当前线程的名字
setName()设置线程名称
yield()释放当前线程的执行权
join()当前线程进行插队,另一线程进入阻塞状态,知道调用线程执行完成
stop()强制结束当前线程(已过时)
sleep()阻塞当前线程(毫秒)
isAlive()线程是否存活
优先级
setPriority()设置优先级
/**
* The minimum priority that a thread can have.
*/
public final static int MIN_PRIORITY = 1;
/**
* The default priority that is assigned to a thread.
*/
public final static int NORM_PRIORITY = 5;
/**
* The maximum priority that a thread can have.
*/
public final static int MAX_PRIORITY = 10;
卖票问题
2.实现Runnable,synchronizaed同步代码块解决线程安全问题
class Window1 implements Runnable{
private static int ticket = 100;
@Override
public void run() {
while (true){
synchronized (this){
if(ticket>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+": 票号 :"+ticket);
ticket--;
}else {
break;
}
}
}
}
}
public class Wondows1Test {
public static void main(String[] args) {
Window1 window1 = new Window1();
Thread t1 = new Thread(window1);
Thread t2 = new Thread(window1);
Thread t3 = new Thread(window1);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
懒汉式单例模式 解决线程安全问题
public class BankTest {
}
class Bank{
private Bank(){
}
private static Bank instance = null;
public static Bank getInstance() {
if (instance == null) {
synchronized (Bank.class) {
if (instance == null) {
instance = new Bank();
}
return instance;
}
}
return instance;
}
}
线程死锁
两个线程互相拿着对方需要的锁
Lock锁
synchronizaed和Lock的异同
相同点 :都能解决线程安全问题
不同点:synchronized机制在执行完相应的同步代码以后,自动的释放同步监视器
Lock需要手动的启动同步(lock()),同时结束同步也需要手动的实现(unlock())
如何实现线程的通信
1.wait(),notify(),notifyAll()三个方法必须使用在同步代码块或同步方法中。
- 2.wait(),notify(),notifyAll()三个方法的调用者必须是同步代码块或同步方法中的同步监视器。
- 否则,会出现IllegalMonitorStateException异常
- 3.wait(),notify(),notifyAll()三个方法是定义在java.lang.Object类中。
- 面试题:sleep() 和 wait()的异同?
- 1.相同点:一旦执行方法,都可以使得当前的线程进入阻塞状态。
- 2.不同点:
- 1)两个方法声明的位置不同:Thread类中声明sleep() , Object类中声明wait()
- 2)调用的要求不同:sleep()可以在任何需要的场景下调用。 wait()必须使用在同步代码块或同步方法中
- 3)关于是否释放同步监视器:如果两个方法都使用在同步代码块或同步方法中,sleep()不会释放锁,wait()会释放锁。