java多线程总结
Posted shaoyu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java多线程总结相关的知识,希望对你有一定的参考价值。
一、java多线程创建的两种方式
1.1、使用Thread类的子类
public class ThreadA extends Thread {
// 在java中可以试用Thread类的子类创建线程,需要重写父类的run方法
@Override
public void run() {
for(int i=0;i<20;i++)
System.out.print("子线程A"+i+" ");
}
}
@Test
public void hello(){
//调用直接创建实现,调用start方法即可
ThreadA threadA = new ThreadA();
threadA.start();
}
1.2、使用Thread类
@Test
public void hello(){
//使用Thread类必须在创建线程对象时向构造方法中传递一个Runnable接口类的实例
new Thread(new Runnable() {
//当线程调用start方法时,就会自动调用run方法
@Override
public void run() {
for(int i=1;i<20;i++)
System.out.print("Runnable "+i+" ");
}
}).start();
}
二、目标对象与线程的关系
2.1、目标对象和线程完全解耦
public static void main(String[] args){
House house = new House();
house.setNun(10);
Thread a,b;
a = new Thread(house);
b = new Thread(house);
a.setName("A");
b.setName("B");
a.start();
b.start();
}
public class House implements Runnable {
int nun;
public void setNun(int nun) {
this.nun = nun;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
while (true){
if("A".equals(name)){
System.out.println(name+"抢票2张");
this.nun = this.nun -2;
}else if("B".equals(name)){
System.out.println(name+"抢票1张");
this.nun--;
}
System.out.println("还剩 "+ nun +" 张");
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(nun <= 0)
return;
}
}
}
2.2、目标对象组合线程(弱耦合)
public static void main(String[] args){
House house = new House();
house.student.start();
house.teacher.start();
}
public class House implements Runnable {
Thread student,teacher;
public House(){
student = new Thread(this);
teacher = new Thread(this);
student.setName("张三");
teacher.setName("王教授");
}
@Override
public void run() {
if(Thread.currentThread() == student){
System.out.println(student.getName() + "正在睡觉,不听讲");
try {
Thread.sleep(1000*60*60);
} catch (InterruptedException e) {
System.out.println(student.getName() + "被老师叫醒了");
}
}else if(Thread.currentThread() == teacher){
for(int i=0; i<3; i++){
System.out.println("上课!");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
student.interrupt();
}
}
}
以上是关于java多线程总结的主要内容,如果未能解决你的问题,请参考以下文章