实现多线程的两种方法:
继承Thread类
实现Runnable接口
(JDK1.5之后提供了一个心得Callable接口)
在启动多线程的时候必须通过start()方法,而不能直接调用run()方法
原因:先来看下start()方法在Thread类中的定义:
public synchronized void start(){
if(threadStatus!=0)
throw new IllegalThreadStateException();
...
start0();
...
}
private native void start0();
start()方法调用时会抛出“IllegalThreadStateException”异常,一般在重复调用的时候会抛出,而实际上正真调用的是start()方法。此方法在声明时使用了native关键字声明,表示调用本机的操作系统函数。因为多线程需要依靠底层操作系统的支持。
一个类如果只能继承Thread类才能实现多线程,则肯定会受到单继承的局限,所以一般来说,要实现多线程,可以通过实现Runnable接口完成;
实现Runnable接口可以资源共享
package thread;
/**
* 实现Runnable接口可以资源共享
*
*/
public class BaseThread implements Runnable{
private int ticket = 5;
@Override
public void run() {
for(int i=0;i<20;i++){
if(ticket>0){
System.out.println("卖票:ticket = "+ticket--);
}
}
}
public static void main(String[] args) {
BaseThread my = new BaseThread();
//启动3个线程
new Thread(my).start();
new Thread(my).start();
new Thread(my).start();
}
}
结果:
卖票:ticket = 5
卖票:ticket = 3
卖票:ticket = 4
卖票:ticket = 1
卖票:ticket = 2
线程的休眠 线程的中断
package thread;
/**
* 线程的休眠
* 线程的中断
*
*/
public class InterruptThread implements Runnable{
@Override
public void run() {
System.out.println("1.进入run方法!");
try {
Thread.sleep(10000);
System.out.println("2.已完成休眠!");
} catch (InterruptedException e) {
System.out.println("3.休眠被终止!");
return;
}
System.out.println("4.run方法正常结束!");
}
public static void main(String[] args) {
InterruptThread my = new InterruptThread();
Thread t =new Thread(my);
t.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
t.interrupt();
}
}
线程的强制运行
package thread;
/**
* 线程的强制运行
*
*/
public class JoinThread implements Runnable{
@Override
public void run() {
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"运行 -->" +i);
}
}
public static void main(String[] args) {
JoinThread my = new JoinThread();
//启动3个线程
Thread t =new Thread(my);
t.start();
for (int i = 0; i < 10; i++) {
if(i>5){
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"运行main -->" +i);
}
}
}
线程礼让
package thread;
/**
* 线程礼让
*
*/
public class YieldThread implements Runnable{
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()+"运行:--->"+i);
if (i==3) {
System.out.println("线程礼让:");
Thread.currentThread().yield();
}
}
}
public static void main(String[] args) {
YieldThread my = new YieldThread();
Thread t1 =new Thread(my,"线程1");
Thread t2 =new Thread(my,"线程2");
t1.start();
t2.start();
}
}
多线程案例(设计一个生产与消费的程序,要求,生产一台,就消费一台,如果没有新的,就等待生产出来,在消费,如果生产出来的没有被消费,则等待消费之后再生产。)https://blog.csdn.net/weixin_42476601/article/details/84193604
模拟竞拍、抢答器:https://blog.csdn.net/weixin_42476601/article/details/84193604