1.用多线程模拟火车售票联网系统,要求多个线程每隔2秒出一次票。
创建SellTicket类来模拟一个线程的出票过程
class SellTicket extends Thread{
private static int id = 0;
@Override
public void run() {
try {
for (int i = 0; i < 50; i++) {
Thread.sleep(3000);
sell();
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
public synchronized void sell() {
id++;
System.out.println(currentThread().getName() + "出票成功!");
}
}
创建线程实例对象并使线程进入就绪状态
public class SaleDemo {
public static void main(String[] args) {
SellTicket st1 = new SellTicket();
st1.setName("窗口1");
st1.start();
SellTicket st2 = new SellTicket();
st2.setName("窗口2");
st2.start();
SellTicket st3 = new SellTicket();
st3.setName("窗口3");
st3.start();
}
}
2.编写具有3个不同优先级线程的程序,3个线程分别输出10个a、b、c,每次输出一个轮回便停止500ms
创建Demo类模拟10次输出
class Demo extends Thread {
String message;
Demo(String message) {
this.message = message;
}
@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
System.out.println(message + "的线程优先级是:" + getPriority());
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
创建线程实例并为其设置相应优先级,线程a由于设置了最高优先级,因此在每次循环中均较为优先地输出
public class MyThread{
public static void main(String[] args) {
Thread t1 = new Demo("线程a");
t1.setPriority(Thread.MAX_PRIORITY);
//MAX_PRIORITY 线程可以具有的最高优先级
t1.start();
Thread t2 = new Demo("线程b");
t2.setPriority(Thread.NORM_PRIORITY);
//NORM_PRIORITY 分配给线程的默认优先级
t2.start();
Thread t3 = new Demo("线程c");
t3.setPriority(Thread.MIN_PRIORITY);
//MIN_PRIORITY 线程可以具有的最低优先级
t3.start();
}
}