创建方式
有两种方式来创建一个线程类,分别是继承Thread类和继承Runnable接口。二者创建实例的方式有所不同。
- 通过继承线程类Thread来创建线程类
class runner1 extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("runner1");
}
}
}
public class Main {
public static void main(String[] args) {
runner1 r1 = new runner1();
runner1 r2 = new runner1();
r1.start();
r2.start();
}
}
- 建立一个实现Runnable接口的类来创建线程
class runner2 implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("runner2");
}
}
}
public class Main {
public static void main(String[] args) {
Thread r1 = new Thread(new runner2());
Thread r2 = new Thread(new runner2());
r1.start();
r2.start();
}
}
设置优先级
可以通过调用setPriority()来设置一个进程的优先级,Thread定义了其中3个常数。
- MAX_PRIORITY,最大优先级(值为10)
- NORM_PRIORITY,默认优先级(值为5)
- MIN_PRIORITY,最小优先级(值为1)
同步锁-synchronized关键字
synchronized关键字可以保证被它修饰的方法或者代码块在任意时刻只能有一个线程执行。
以一个模拟售票程序为例:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Share share = new Share(100);
for (int i = 0; i < 5; i++) {
new Seller(share, i + 1).start();
}
}
}
class Share {
public int maxn;
public int rest;
public Share(int n) {
rest = n;
maxn = n;
}
public synchronized boolean get_ticket(int id) {
if (rest > 0) {
System.out.println(id + "号窗口卖出一张票,剩余" + --rest + "张票");
return true;
}
return false;
}
}
class Seller extends Thread {
private Share shared;
private int id;
public Seller(Share share, int id) {
this.shared = share;
this.id = id;
}
public void run() {
while (shared.get_ticket(id)) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
运行截图
如果把同步锁去掉,再次运行:
可以发现剩余的票数不是有序的了,因此可能会出现同一张票被两个窗口同时卖出的清空。