1.继承Thread类的多线程
基础步骤
- 继承Thread类
- 重写Run()方法
- 实例化线程对象
- 开启线程 调用start()方法
经典买票案例,你值得拥有
下面为实现代码:
public class ThreadDemo extends Thread {
public static int piao = 100;
public Object object;//同步锁对象
@Override
public void run() {
while (true) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
//同步锁
synchronized (object){
if (piao>0){
try {
Thread.sleep(100);
piao--;
System.out.println(Thread.currentThread().getName()+"窗口卖一张票数,"+"还剩下"+piao+"张票");
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
break;
}
}
}
}
}
**测试**
public class ThreadTest {
public static void main(String[] args) {
Object o = new Object();
//实例化实现类对象
ThreadDemo thread1 = new ThreadDemo();
thread1.setName("一号窗口");
thread1.object = o;
ThreadDemo thread2 = new ThreadDemo();
thread2.setName("二号窗口");
thread2.object = o;
ThreadDemo thread3= new ThreadDemo();
thread3.setName("三号窗口");
thread3.object = o;
ThreadDemo thread4 = new ThreadDemo();
thread4.setName("四号窗口");
thread4.object = o;
//开启线程
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
2.实现Runnable接口的多线程
基础步骤
- 实现Runnable接口
- 重写Run()方法
- 实例化实现类对象转换为线程对象(与继承Thread类的区别)
- 开启线程 调用start()方法
测试方法的实现 经典买票案例 哪里用都牛气
public class RunnableDemo implement Runnable {
public static int piao = 100;
public Object object;
@Override
public void run() {
while (true) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object){
if (piao>0){
try {
Thread.sleep(100);
piao--;
System.out.println(Thread.currentThread().getName()+"窗口卖一张票数,"+"还剩下"+piao+"张票");
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
break;
}
}
}
}
public static void main(String[] args) {
Object o = new Object();
//实例化实现类对象
RunnableDemo runnableDemo1 = new RunnableDemo();
runnableDemo1.object = o;
//创建线程
Thread thread1 =new Thread("一号窗口");
Thread thread2 =new Thread("二号窗口");
Thread thread3 =new Thread("三号窗口");
Thread thread4 = new Thread("四号窗口");
//开启线程
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
以上便是两种简单的实现多线程的方法,通俗易懂,代码中并没有详细的注释,如果你知道了单线程,那么这个多线程是很容易理解的,如果看不懂,就动手做一下代码测试,就会明了,就会走上人生巅峰 ,就会迎…算了 。如有错误,请指正,谢谢。
注意:
1.调用start方法开启线程,那么线程会执行run方法中所有的内容.
2.一个类实现Runnable接口,那么该类还是一个普通类.
3.一个类继承Thread类,那么该类是一个线程类.
谢谢观看