程序
是为完成特定任务、用某种语言编写的一组指令的集合(简单来说就是写的代码)。
进程
什么是线程
其他相关概念
在Java线程创建有两种方式:
public class Thread01 {
public static void main(String[] args) {
Cat cat = new Cat();
//启动线程,最终会执行cat的run方法
cat.start();
}
static class Cat extends Thread {
int time = 0;
@Override
public void run() {
while (true) {
System.out.println("喵喵,我是小猫咪" + (++time));
try {
//线程休眠1秒
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (time == 8) {
break;
}
}
}
}
}
在main里面建立一个循环,此时main线程和main建立的Thread0线程交替执行(并发),主线程不会阻塞。进程可以创建线程,线程也可以创建线程。只有所有线程执行结束,进程才会挂掉。
public class Thread01 {
public static void main(String[] args) throws InterruptedException {
//创建Cat对象,可以当做线程使用
Cat cat = new Cat();
cat.start();//启动线程-> 最终会执行cat的run方法
System.out.println("主线程继续执行" + Thread.currentThread().getName());//名字main
for(int i = 0; i < 60; i++) {
System.out.println("主线程 i=" + i);
//让主线程休眠
Thread.sleep(1000);
}
}
}
class Cat extends Thread {
int times = 0;
@Override
public void run() {//重写run方法,写上自己的业务逻辑
while (true) {
//该线程每隔1秒。在控制台输出 “喵喵, 我是小猫咪”
System.out.println("喵喵, 我是小猫咪" + (++times) + " 线程名=" + Thread.currentThread().getName());
//让该线程休眠1秒 ctrl+alt+t
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(times == 80) {
break;//当times 到80, 退出while, 这时线程也就退出..
}
}
}
}
问题:启动线程为什么调用start方法,而不是run方法?
run方法只是一个普通的方法,没有真正的启动一个线程,如果调用cat.run(),就会把run方法执行完毕后,才向下执行(串行)。
而调用cat.start(),会启动线程,最终在线程内执行cat的run方法。
外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传
Java是单继承的,在某些情况下,一个类可能已经继承了某一个父类,这时候如果想要创建线程只能通过实现接口来创建。
因为Runable接口当中只有run()方法,因此不能直接调用start()方法,所以需要一个代理完成该方法的调用。
public class Thread02 {
public static void main(String[] args) {
Dog dog = new Dog();
//dog.start(); 这里不能调用start
//创建了Thread对象,把 dog对象(实现Runnable),放入Thread
Thread thread = new Thread(dog);
thread.start();
}
}
class Dog implements Runnable { //通过实现Runnable接口,开发线程
int count = 0;
@Override
public void run() { //普通方法
while (true) {
System.out.println("小狗汪汪叫..hi" + (++count) + Thread.currentThread().getName());
//休眠1秒
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (count == 10) {
break;
}
}
}
}
模拟代理
//线程代理类 , 模拟了一个极简的Thread类
class ThreadProxy implements Runnable {//你可以把Proxy类当做 ThreadProxy
private Runnable target = null;//属性,类型是 Runnable
@Override
public void run() {
if (target != null) {
target.run();//动态绑定(运行类型Tiger)
}
}
public ThreadProxy(Runnable target) {
this.target = target;
}
public void start() {
start0();//这个方法时真正实现多线程方法
}
public void start0() {
run();
}
}
class Animal {
}
class Tiger extends Animal implements Runnable {
@Override
public void run() {
System.out.println("老虎嗷嗷叫....");
}
}
public class Thread02 {
public static void main(String[] args) {
Tiger tiger = new Tiger();//实现了 Runnable
ThreadProxy threadProxy = new ThreadProxy(tiger);
threadProxy.start();
}
}
public class Thread03 {
public static void main(String[] args) {
T1 t1 = new T1();
T2 t2 = new T2();
Thread thread1 = new Thread(t1);
Thread thread2 = new Thread(t2);
thread1.start();
thread2.start();
}
}
class T1 implements Runnable{
int count=0;
@Override
public void run() {
while (true){
System.out.println(Thread.currentThread().getName()+":hello"+(++count));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (count==5){
break;
}
}
}
}
class T2 implements Runnable{
int count=0;
@Override
public void run() {
while (true){
System.out.println(Thread.currentThread().getName()+":hi"+(++count));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (count==10){
break;
}
}
}
}
注意:线程全部结束,该进程才会结束。
下图程序当中,线程thread01和thread02就共享了t3。
public class SellTicket {
public static void main(String[] args) {
SellTicketByRunnable sellTicketByRunnable = new SellTicketByRunnable();
new Thread(sellTicketByRunnable).start();//第1个线程-窗口
new Thread(sellTicketByRunnable).start();//第2个线程-窗口
new Thread(sellTicketByRunnable).start();//第3个线程-窗口
}
}
class SellTicketByRunnable implements Runnable {
//让多个线程共享TICKET_NUMBER
private static int TICKET_NUMBER = 100;
@Override
public void run() {
while (true) {
if (TICKET_NUMBER <= 0) {
System.out.println("售票结束");
break;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("窗口:" + Thread.currentThread().getName() + "售出一张票,剩余票数=" + (--TICKET_NUMBER));
}
}
}
可能会出现多售票的情况,因为线程不是同步的。
假设剩余一张票,三个线程可能同时进去,这样会出现多卖问题。
基本说明
应用实例
/**
* 线程终止
*/
public class ThreadExit {
public static void main(String[] args) throws Exception {
T t = new T();
t.start();
//让主线程休眠10s
Thread.sleep(10 * 1000);
t.setLoop(false);
}
}
class T extends Thread {
int count = 0;
//设置一个控制变量
Boolean loop = true;
public void setLoop(Boolean loop) {
this.loop = loop;
}
@Override
public void run() {
while (loop) {
System.out.println("T正在运行中 " + (++count));
try {
Thread.sleep(50);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
public class ThreadMethod01 {
public static void main(String[] args) throws Exception {
T t = new T();
t.setName("汤姆");
t.setPriority(Thread.MIN_PRIORITY);
t.start();
//主线程打印5个hi ,然后就中断子线程的休眠
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("hi " + i);
}
System.out.println(t.getName() + "线程的优先级= " + t.getPriority());
t.interrupt();
}
}
class T extends Thread {
@Override
public void run() {
while (true) {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " 在学线程.." + i);
}
try {
System.out.println(Thread.currentThread().getName() + " 在休眠中..");
Thread.sleep(10000);
} catch (InterruptedException e) {
//当该线程执行到一个interrupt 方法时,就会catch 一个 异常, 可以加入自己的业务代码
//InterruptedException 是捕获到一个中断异常
System.out.println(Thread.currentThread().getName() + "被interrupt了");
}
}
}
}
start底层会创建新的线程,调用run,run就是一个简单的方法调用,不会启动新线程。
线程优先级的范围
interrupt是中断线程,但没有真正的结束线程,所以一般用于中断正在休眠的线程。
sleep是线程的静态方法,使当前线程休眠。
yield:线程礼让
让出CPU,让其他线程执行,但是礼让的时间不确定,所以礼让不一定成功。
join:线程插队
插队的线程一旦成功,则肯定先执行完插入的线程所有的任务后,再去执行自己的任务。
案例
主线程和子线程同时吃10个苹果,当他们俩都吃到第五个的时候,主线程让子线程先吃,子线程吃完了主线程再吃。
/**
* 线程礼让和插队
*/
public class ThreadMethod02 {
public static void main(String[] args) throws Exception {
T1 t = new T1();
t.start();
for (int i = 1; i <= 10; i++) {
Thread.sleep(999);
System.out.println("主线程吃了 " + i + " 个苹果");
if (i == 5) {
System.out.println("子线程插队");
//Thread.yield();//主线程礼让,不一定成功
t.join(); //子线程插队,一定成功
System.out.println("主线程继续执行");
}
}
}
}
class T1 extends Thread {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("子线程吃了 " + i + " 个苹果");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
用户线程
也叫工作线程,当线程的任务执行完或通知方式通知他结束。
守护线程
一般是为了工作线程服务的,当所有的工作线程结束,守护线程自动结束 。常见的守护线程就是垃圾回收机制。
public class ThreadMethod03 {
public static void main(String[] args) throws InterruptedException {
MyDaemonThread myDaemonThread = new MyDaemonThread();
//如果我们希望当main线程结束后,子线程自动结束,只需将子线程设为守护线程即可
myDaemonThread.setDaemon(true);
myDaemonThread.start();
for( int i = 1; i <= 10; i++) {//main线程
System.out.println("宝强在辛苦的工作...");
Thread.sleep(1000);
}
}
}
class MyDaemonThread extends Thread {
public void run() {
for (; ; ) {//无限循环
try {
Thread.sleep(1000);//休眠1000毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("马蓉和宋喆快乐聊天,哈哈哈~~~");
}
}
}
线程有七种状态:
public class ThreadState_ {
public static void main(String[] args) throws InterruptedException {
T t = new T();
System.out.println(t.getName() + " 状态 " + t.getState());
t.start();
while (Thread.State.TERMINATED != t.getState()) {
System.out.println(t.getName() + " 状态 " + t.getState());
Thread.sleep(500);
}
System.out.println(t.getName() + " 状态 " + t.getState());
}
}
class T extends Thread {
@Override
public void run() {
while (true) {
for (int i = 0; i < 10; i++) {
System.out.println("hi " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
break;
}
}
}
同步代码块
synchronized(对象){ //得到对象的锁,才能操作同步代码
//需要被同步代码;
}
同步方法
synchronized还可以放在方法声明中,表示整个方法。
public synchronized void m(String name){
//需要被同步的代码
}
注意:不能直接在run()方法前加synchronized,因为这样会使得只有一个窗口可以进入卖票,使得其他窗口一直处于锁死状态,直至票卖完退出。
public class SellTicket {
public static void main(String[] args) {
SellTicketByRunnable sellTicketByRunnable = new SellTicketByRunnable();
new Thread(sellTicketByRunnable).start();//第1个线程-窗口
new Thread(sellTicketByRunnable).start();//第2个线程-窗口
new Thread(sellTicketByRunnable).start();//第3个线程-窗口
}
}
class SellTicketByRunnable implements Runnable {
//让多个线程共享TICKET_NUMBER
private static int TICKET_NUMBER = 100;
private Boolean loop = true;
public synchronized void sell() {
if (TICKET_NUMBER <= 0) {
System.out.println("售票结束");
loop=false;
return;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("窗口:" + Thread.currentThread().getName() + "售出一张票,剩余票数=" + (--TICKET_NUMBER));
}
@Override
public void run() {
while (loop) {
sell();
}
}
}
代码示例-实现接口的同步
方法一:在方法上添加synchronized修饰,默认锁在this对象
方法二:在方法内部设置同步代码块添加修饰,锁可以在this对象(或者自己创建的Object对象),也可以在其他对象,但是必须是同一个对象,若不是同一个对象,那么不同线程操作的对象就不同了,就不存在同步问题了。
方法三:在静态方法内设置synchronized修饰的同步代码块,默认锁在该类
方法四:在静态方法上添加synchronized修饰,默认锁在该类
代码示例-继承类的同步
方法一:静态方法直接写synchronized修饰,默认锁在该类
方法二:静态方法内部写同步代码块,默认的锁在该类
多个线程都占用了对方的资源,都不肯相让,导致了死锁,在编程中一定要避免死锁的发生。
public class DeadLock_ {
public static void main(String[] args) {
//模拟死锁现象
DeadLockDemo A = new DeadLockDemo(true);
A.setName("A线程");
DeadLockDemo B = new DeadLockDemo(false);
B.setName("B线程");
A.start();
B.start();
}
}
//线程
class DeadLockDemo extends Thread {
static Object o1 = new Object();// 保证多线程,共享一个对象,这里使用static
static Object o2 = new Object();
boolean flag;
public DeadLockDemo(boolean flag) {//构造器
this.flag = flag;
}
@Override
public void run() {
//下面业务逻辑的分析
//1. 如果flag 为 T, 线程A 就会先得到/持有 o1 对象锁, 然后尝试去获取 o2 对象锁
//2. 如果线程A 得不到 o2 对象锁,就会Blocked
//3. 如果flag 为 F, 线程B 就会先得到/持有 o2 对象锁, 然后尝试去获取 o1 对象锁
//4. 如果线程B 得不到 o1 对象锁,就会Blocked
if (flag) {
synchronized (o1) {//对象互斥锁, 下面就是同步代码
System.out.println(Thread.currentThread().getName() + " 进入1");
synchronized (o2) { // 这里获得li对象的监视权
System.out.println(Thread.currentThread().getName() + " 进入2");
}
}
} else {
synchronized (o2) {
System.out.println(Thread.currentThread().getName() + " 进入3");
synchronized (o1) { // 这里获得li对象的监视权
System.out.println(Thread.currentThread().getName() + " 进入4");
}
}
}
}
}
下面操作会释放锁
下面操作不会释放锁
线程执行同步代码块或同步方法时,程序调用Thread.sleep(),Thread.yield()方法暂停当前线程的执行,不会释放锁。
线程执行同步代码块时,其他线程调用了该线程的suspend()方法将该线程挂起,该线程不会释放锁。
提示:不推荐使用suspend()和resume()来控制线程。
练习二
public class Homework01 {
public static void main(String[] args) {
A a = new A();
B b = new B(a);//一定要注意.
a.start();
b.start();
}
}
//创建A线程类
class A extends Thread {
private boolean loop = true;
@Override
public void run() {
//输出1-100数字
while (loop) {
System.out.println((int)(Math.random() * 100 + 1));
//休眠
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("a线程退出...");
}
public void setLoop(boolean loop) {//可以修改loop变量
this.loop = loop;
}
}
//直到第2个线程从键盘读取了“Q”命令
class B extends Thread {
private A a;
private Scanner scanner = new Scanner(System.in);
public B(A a) {//构造器中,直接传入A类对象
this.a = a;
}
@Override
public void run() {
while (true) {
//接收到用户的输入
System.out.println("请输入你指令(Q)表示退出:");
char key = scanner.next().toUpperCase().charAt(0);
if(key == 'Q') {
//以通知的方式结束a线程
a.setLoop(false);
System.out.println("b线程退出.");
break;
}
}
}
}
练习二
public class Homework02 {
public static void main(String[] args) {
T t = new T();
Thread thread1 = new Thread(t);
thread1.setName("t1");
Thread thread2 = new Thread(t);
thread2.setName("t2");
thread1.start();
thread2.start();
}
}
//编程取款的线程
//1.因为这里涉及到多个线程共享资源,所以我们使用实现Runnable方式
//2. 每次取出 1000
class T implements Runnable {
private int money = 10000;
@Override
public void run() {
while (true) {
//解读
//1. 这里使用 synchronized 实现了线程同步
//2. 当多个线程执行到这里时,就会去争夺 this对象锁
//3. 哪个线程争夺到(获取)this对象锁,就执行 synchronized 代码块, 执行完后,会释放this对象锁
//4. 争夺不到this对象锁,就blocked ,准备继续争夺
//5. this对象锁是非公平锁.
synchronized (this) {//
//判断余额是否够
if (money < 1000) {
System.out.println("余额不足");
break;
}
money -= 1000;
System.out.println(Thread.currentThread().getName() + " 取出了1000 当前余额=" + money);
}
//休眠1s
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}