继承线程类
public class MultiThreadExample{
public static void main(String []args){
new MyThread("A").start();//启动线程A
new MyThread("B").start();//启动线程B
}
}
class MyThread extends Thread{
public MyThread(String n){
super(n); //线程名称
}
public void run(){
for(int i=0;i<5;i++){
try{
// 睡眠一段随机时间
Thread.sleep((long)(Math.random() * 1000));
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.print(getName()); //打印线程名称
}
}
}
运行结果:
ABABBAAABB
实现Runnable接口
public class MultiThreadExample2{
public static void main(String []args){
Thread t1=new Thread(new CustomThread("A"));
Thread t2=new Thread(new CustomThread("B"));
t1.start();//启动线程A
t2.start();//启动线程B
}
}
class CustomThread implements Runnable{
String name;
public CustomThread(String n){
name=n;
}
public void run(){
Thread current=Thread.currentThread();//取得当前线程
for(int i=0;i<5;i++){
try{
// 睡眠一段随机时间
current.sleep((long)(Math.random() * 1000));
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.print(name); //打印线程名称
}
}
}
运行结果:
BABBAABABA
模拟火车站售票
- 三个售票口老师同时卖100张火车票,每个售票口相当于一个线程。
class Window extends Thread{
static int ticket = 100;
public void run(){
while (true) {
if (ticket>0) {
System.out.println(Thread.currentThread().getName()+"售票,票号为:"+ticket--);
}else {
break;
}
}
}
}
public class TestWindow {
public static void main(String[] args) {
Window w1 = new Window();
Window w2 = new Window();
Window w3 = new Window();
w1.setName("窗口1");
w2.setName("窗口2");
w3.setName("窗口3");
w1.start();
w2.start();
w3.start();
}
}
模拟多个人通过一个山洞
- 这个山洞每次只能通过一个人,每个人通过山洞的时间为5秒
- 随机生成5个人,同时准备过此山洞,显示一下每次通过山洞人的姓名
public class Test02 {
public static void main(String[] args) {
//实例化山洞
Shandong shandong = new Shandong();
//创建10个线程
Thread thread1 = new Thread(shandong, "1");
Thread thread2 = new Thread(shandong, "2");
Thread thread3 = new Thread(shandong, "3");
Thread thread4 = new Thread(shandong, "4");
Thread thread5 = new Thread(shandong, "5");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
//山洞
class Shandong extends Thread{
@Override
public void run() {
//上锁
synchronized(this){
System.out.println(Thread.currentThread().getName()+"正在通过,请等待5s");
try {
sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}