一、继承Thread类创建
通过继承Thread并且重写其run()方法,通过调用 start() 方法即可执行线程方法。
写法1:
public class MyThread extends Thread {
@Override
public void run() {
for ( int i = 0;i < 15; i++) {
System.out.println(getName()+"执行任务线程"+i);
}
}
public static void main(String[] args) {
for (int i = 0; i <10 ; i++) {
new MyThread().start();
}
}
}
二、 通过Runnable接口创建线程类
该方法需要实现Runnable接口,并重写该接口的 run() 方法
public static void main(String[] args) {
new Thread(new MyThread()).start();
new Thread(new MyThread()).start();
}
@Override
public void run() {
for (int i = 0; i <10 ; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
写法2:
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread);
thread.start();
for (int i = 10; i <20 ; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+"执行任务:"+i);
}
}
三、通过创建三个用户抢夺,购票权限,实现同步锁操作,解决超发问题;
public class MyThread implements Runnable {
private int ticker = 100;
public static void main(String[] args) {
MyThread myThread = new MyThread();
new Thread(myThread).start();
new Thread(myThread).start();
new Thread(myThread).start();
}
@Override
public void run() {
while (true) {
//同步代码块实现同步锁,解决超卖问题
synchronized (MyThread.class){
if (ticker > 0) {
System.out.println(Thread.currentThread().getName() + "发票:" + ticker);
ticker--;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
自定义lock锁机制,开始和结束,手动控制
public class LockThread {
//定义票数
private static int tikcer = 30;
//自定义开启锁和关闭锁
public static void main(String[] args) {
ReentrantLock lock = new ReentrantLock();
Runnable runnable = new Runnable() {
@Override
public void run() {
while (true) {
//开启锁
lock.lock();
try {
if (tikcer > 0) {
System.out.println(Thread.currentThread().getName() + "---剩余票数:" + tikcer);
tikcer--;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭锁
lock.unlock();
}
}
}
};
new Thread(runnable).start();
new Thread(runnable).start();
new Thread(runnable).start();
}
}