创建线程主要常用有两种方式,一是继承Thread,二是实现Runnable接口
继承Thread
package cn.ITShark;
public class EX_Thread02 {
public static void main(String[] args) {
Thread t1=new mythread();
t1.setName("子线程01");
t1.start();
Thread t2=new mythread();
t2.setName("子线程02");
t2.start();
Thread t=Thread.currentThread();//currentThread()在哪个线程里面执行就返回哪个线程的对象
System.out.println(t.getName());
}
}
class mythread extends Thread{
public void run(){
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+"执行第"+i+"次");
}
}
}
-注意:
1、main方法也是一个线程,是主线程,t1,t2不过都是在主线程里面运行而已;
2、t1,t2只有调用start()方法才可以开启线程,只是调用run()的话就只是调用一个方法而已,跟普通类没区别
实现Runnable接口
package cn.ITShark;
public class EX_Thread03 {
public static void main(String[] args) {
//创建线程任务对象,不是线程对象
Runnable runnable=new MyRunnable();
//创建线程对象
Thread t1=new Thread(runnable,"子线程1");
t1.start();
Thread t2=new Thread(runnable,"子线程2");
t2.start();
}
}
class MyRunnable implements Runnable{
public void run(){
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+"执行第"+i+"次");
}
}
}
- 其实跟第一种差不多,多了一步创建线程任务对象,因为java是单继承的,假设一个类已经继承了其他类,那就不能再去继承Thread了,这时用Runnable
实例演练:
模仿账户取钱:
Account.java:
package cn.ITShark.THREAD;
public class Account {
private int CardID;
private int money;
public Account(int cardID, int money) {
CardID = cardID;
this.money = money;
}
public Account() {
}
public int getCardID() {
return CardID;
}
public void setCardID(int cardID) {
CardID = cardID;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public void Drawmongey(int money) {
String name=Thread.currentThread().getName();
//使用同步机制,使得每次只能一个人取钱
synchronized (this) {
if (this.money >= money) {
System.out.println(name + "取钱,钱足够,取走:" + money + " 剩余:");
this.money -= money;
System.out.println(this.money);
} else
System.out.println(name+"来取钱,钱不够");
}
}
}
User.java:
package cn.ITShark.THREAD;
public class User {
public static void main(String[] args) {
//初始化账户的基本信息--账号id和余额
Account ac=new Account(123,10000);
//可以使用此账户的人
Thread Dad=new Bank(ac,"Dad");
Dad.start();
Thread Mom=new Bank(ac,"Mom");
Mom.start();
}
}
Bank.java:
package cn.ITShark.THREAD;
public class Bank extends Thread {
private Account acc;
public Bank(Account acc,String name){
super(name);
this.acc=acc;
}
//取钱操作
public void run(){
acc.Drawmongey(10000);
}
}