进程:一个应用程序在内存中执行区域
线程:进程中的一个执行控制单元
单线程:安全性高,效率低
多线程:安全性低,效率高
主方法main是单线程的(在主方法可以创建多线程)
实现方法
一:继承Thread类
二:实现Runable接口
==================================================================
案例:
/**
* 模拟售票
* 出现的问题:
* 多个线程并发访问相同资源
* 解决方法:
* synchronized:同步(锁)
* 同步:安全性高、效率低
*/
public class TicketTest {
public static void main(String[] args) {
//创建线程对象
TicketThread tt=new TicketThread();
Thread t1=new Thread(tt);
t1.setName("窗口一");
Thread t2=new Thread(tt);
t2.setName("窗口二");
Thread t3=new Thread(tt);
t3.setName("窗口三");
t1.start();
t2.start();
t3.start();
}
}
//同步代码块
public class TicketThread implements Runnable{
int tickets=100;//火车票数量
Object obj=new Object();
@Override
public void run() {
synchronized (obj) {
//出售火车票
while(true) {
if(tickets>0) {
try {
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+" 剩余票数:"+tickets--);
} catch (Exception e) {
}
}
}
}
}
}
//同步方法
//非静态锁对象是this
//静态锁对象是当前类字节码对象
public class TicketThread implements Runnable{
int tickets=100;//火车票数量
Object obj=new Object();
@Override
public void run() {
method();
}
private synchronized void method() {
//出售火车票
while(true) {
if(tickets>0) {
try {
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+" 剩余票数:"+tickets--);
} catch (Exception e) {
}
}
}
}
}