1、什么是线程和进程?
进程:是指正在运行的程序。进程具有独立性、动态性和并发性。
- 独立性:进程是一个能独立运行的基本单位,同时也是系统分配资源和调度的独立单位
- 动态性:进程的实质是程序的一次执行过程,进程是动态产生,动态消亡的
- 并发性:任何进程都可以同其他进程一起并发执行
线程:又称轻量级进程(Light Weight Process)。线程是进程中的一条执行路径,也是CPU的基本调度单位。一个进程由一个或多个线程组成,彼此间完成不同的工作(任务),他们同时执行,就被称为多线程。
使用多线程的意义就是为了充分利用cpu资源,提高程序运行效率。
2、JAVA如何创建多线程?
java提供了三种实现多线程的方法,分别是继承Thread类、实现Runnable接口以及实现Callable接口。
2.1 方式一:通过继承Thread类
实现步骤:
-
定义一个类MyThread继承Thread类
-
在MyThread类中重写run()方法
-
创建MyThread类的对象
-
启动线程
代码实现:
//创建一个线程类
public class MyThread extends Thread{
//run表示线程启动后执行的业务代码
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("~~~~~~~~~~~~~~~~~~"+i);
}
}
}
public class Test01 {
public static void main(String[] args) {
//创建线程对象
MyThread my=new MyThread();
//开启线程--硬件底层调用线程的run方法
my.start();
for (int i = 0; i < 20; i++) {
System.out.println("main~~~~~~~~~~~~~"+i);
}
}
}
实际案例:
使用Thread类实现4窗口各卖100张票
public class SellTicket extends Thread {
private int tick=100;
@Override
public void run() {
while (true){
if(tick>0){
tick--;
System.out.println(Thread.currentThread().getName()+"卖了一张票,剩余:"+tick+"张");
}else{
System.out.println(Thread.currentThread().getName()+"卖完了");
break;
}
}
}
}
2.2 方式二:实现Runnable接口
实现步骤:
-
定义一个类MyRunnable实现Runnable接口
-
在MyRunnable类中重写run()方法
-
创建MyRunnable类的对象
-
创建Thread类的对象,把MyRunnable对象作为构造方法的参数
-
启动线程
代码实现:
public class MyRunnable implements Runnable{
@Override
public void run() {
//线程执行时的任务代码
for (int i = 0; i < 20; i++) {
//此处的currentThread方法是用来获取当前线程对象的;getName则是获取线程名
System.out.println(Thread.currentThread().getName()+"~~~~~~~~~~~~~"+i);
}
}
}
public class Test01 {
public static void main(String[] args) {
//创建线程任务对象
MyRunnable my=new MyRunnable();
//创建线程对象
Thread t1=new Thread(my,"线程名");
t1.start();
for (int i = 0; i < 20; i++) {
System.out.println("main+++++++++++++++++++"+i);
}
}
}
实际案例:
使用Thread类实现4窗口共卖100张票
public class SellTicket implements Runnable {
private int tick = 100;
@Override
public void run() {
while (true) {
if (tick > 0) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
tick--;
System.out.println(Thread.currentThread().getName() + "卖了一张票;剩余:" + tick + "张");
} else {
break;
}
}
}
}
public class TestTick {
public static void main(String[] args) {
SellTicket task=new SellTicket();
Thread t1=new Thread(task,"窗口A");
Thread t2=new Thread(task,"窗口B");
Thread t3=new Thread(task,"窗口C");
Thread t4=new Thread(task,"窗口D");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
运行结果:
由结果可以分析出: 会存在超卖和重卖现象。 这是因为多个线程共享一个资源,导致了线程安全隐患问题。后期解决线程安全问题。 后期我们可以使用锁解决。详情请参考另一篇文章如何解决线程安全问题
方式三:
2.3 实现Callable接口
实现步骤
-
定义一个类MyCallable实现Callable接口
-
在MyCallable类中重写call()方法
-
创建MyCallable类的对象
-
创建Future的实现类FutureTask对象,把MyCallable对象作为构造方法的参数
-
创建Thread类的对象,把FutureTask对象作为构造方法的参数
-
启动线程
-
再调用get方法,就可以获取线程结束之后的结果。
代码实现:
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
double sum=0;
for (int i = 0; i < 100; i++) {
//求1--100的和
sum+=i;
}
//返回值就表示线程运行完毕之后的结果
return sum;
}
}
public class Demo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//线程开启之后需要执行里面的call方法
MyCallable mc = new MyCallable();
//可以获取线程执行完毕之后的结果.也可以作为参数传递给Thread对象
FutureTask ft = new FutureTask(mc);
//创建线程对象
Thread t1 = new Thread(ft);
String s = ft.get();
//开启线程
t1.start();
System.out.println(s);
}
}
三种方式对比:
-
实现Runnable、Callable接口
-
好处: 扩展性强,实现该接口的同时还可以继承其他的类
-
缺点: 编程相对复杂,不能直接使用Thread类中的方法
-
-
继承Thread类
-
好处: 编程比较简单,可以直接使用Thread类中的方法
-
缺点: 可以扩展性较差,不能再继承其他的类
-
3、Thread类中的常用方法
3.1 getname():返回此线程的名称
3.2 setName(String name) :将此线程的名称更改为等于参数name
3.3 Thread currentThread():返回对当前正在执行的线程对象的引用
public class MyThread extends Thread {
public MyThread() {}
public MyThread(String name) {
super(name);
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(getName()+":"+i);
}
}
}
public class MyThreadDemo {
public static void main(String[] args) {
MyThread my1 = new MyThread();
MyThread my2 = new MyThread();
//void setName(String name):将此线程的名称更改为等于参数 name
my1.setName("高铁");
my2.setName("飞机");
//Thread(String name)
MyThread my1 = new MyThread("高铁");
MyThread my2 = new MyThread("飞机");
my1.start();
my2.start();
//static Thread currentThread() 返回对当前正在执行的线程对象的引用
System.out.println(Thread.currentThread().getName());
}
}
3.4 线程休眠方法—tatic void sleep
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "---" + i);
}
}
}
public class Demo {
public static void main(String[] args) throws InterruptedException {
/*System.out.println("睡觉前");
Thread.sleep(3000);
System.out.println("睡醒了");*/
MyRunnable mr = new MyRunnable();
Thread t1 = new Thread(mr);
Thread t2 = new Thread(mr);
t1.start();
t2.start();
}
}
3.5 yield 当前线程让出cpu-参与下次的竞争
public class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i <20 ; i++) {
System.out.println(Thread.currentThread().getName()+"~~~~~~~~~~~~~~~"+i);
Thread.yield();//当前线程让出cpu参与下次的竞争。
System.out.println("~~~~~~~~~~~~~~~~");
}
}
}
3.6 join加入当前线程上
插入的线程执行完毕后,当前线程才会执行。
public class Test {
public static void main(String[] args) throws InterruptedException {
MyThread t1=new MyThread();
t1.setName("线程A");
MyThread2 t2=new MyThread2();
t2.setName("线程B");
t1.start();
t2.start();
t1.join(); //t1加入主线程上,主线程需要等t1执行完毕后才会执行. 如果主线程需要等带t1和t2线程的执行结果 做下一步操作时。
for (int i = 0; i <20 ; i++) {
Thread.sleep(10);
System.out.println("main~~~~~~~~~~~~~~~~~~~~~"+i);
}
}
}
3.7 设置线程为守护线程---setDaemon()
当所有线程执行完毕后,守护线程也会终止。JDk就有一个默认的守护线程叫做GC垃圾回收。
public class MyThread1 extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(getName() + "---" + i);
}
}
}
public class MyThread2 extends Thread {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(getName() + "---" + i);
}
}
}
public class Demo {
public static void main(String[] args) {
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
t1.setName("女神");
t2.setName("备胎");
//把第二个线程设置为守护线程
//当普通线程执行完之后,那么守护线程也没有继续运行下去的必要了.
t2.setDaemon(true);
t1.start();
t2.start();
}
}