继承 Thread 类
/**
* Java JVM 启动的时候会有一个进程 java.exe.
* Java 进程中至少有一个线程负责 java 程序的执行, 运行的代码存在于 main() 函数中, 称之为主线程.
* 实际上, JVM 的启动不止一个线程, 还有一个负责垃圾回收的线程.
*/
public class SubsidiaryThread extends Thread {
public void run() {
for (int i = 0; i < 60; i++) {
System.out.println("这是分线程在运行!!!" + i);
}
}
}
public class MainThread {
public static void main(String[] args) {
SubsidiaryThread st = new SubsidiaryThread();
st.start();
for (int i = 0; i < 60; i++) {
System.out.println("这是主线程在运行!!!" + i);
}
}
}
实现 Runnable 接口.java
/**
* 步骤:
* 定义类实现 Runnable 接口,
* 实现 Runnable 接口中的 run 方法,
* 通过 Thread 类建立线程对象,
* 把 Runnable 接口的子类对象, 作为实际的参数传递给 Thread 类构造函数(Thread(Runnable target) 分配新的 Thread 对象),
* 调用 Thread 类的 start() 方法开启线程(自动调用 Runnable 接口子类的 run() 方法).
*/
public class Ticket implements Runnable {
private int ticket = 100;
public void run() {
while(ticket > 0) {
System.out.println(Thread.currentThread().getName() + "-->sale:" + ticket--);
}
}
}
public class MainThread {
public static void main(String[] args) {
Ticket ticket = new Ticket();
/** 启动新的线程对象 **/
new Thread(ticket).start();
new Thread(ticket).start();
new Thread(ticket).start();
new Thread(ticket).start();
}
}
线程插队运行.java
/**
* 在编写多线程程序时, 如果让一个线程优先于其他线程运行的状况, 除了可以设置该线程的优先级高于其他线程外,
* 更直接的方式就是使用 Thread 类的 join() 和 yield() 方法.
*/
public class JoinThread implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread lt = new Thread(new JoinThread());
lt.start();
System.out.println("Hello!");
lt.join();
System.out.println("What the hell just happened?");
}
public void run() {
System.out.println("A");
System.out.println("B");
System.out.println("C");
}
}
/**
* 输出结果为:
* Hello!
* A
* B
* C
* What the hell just happened?
*/
线程死锁.java
/**
* 在编写多线程程序时, 必须注意资源的使用情况, 如果两个线程分别拥有不同的资源, 而又同时需要对方释放资源才能继续运行, 就会导致死锁!
*/
public class DeadLock implements Runnable {
private boolean flag;
private static final Object o1 = new Object();
private static final Object o2 = new Object();
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + ": flag =" + flag);
if (flag == true) {
synchronized(o1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadName + "进入 o1 准备进入 o2");
synchronized(o2) {
System.out.println(threadName + "已经进入 o2");
}
}
}
if (flag == false) {
synchronized(o2) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadName + "进入 o2 准备进入 o1");
synchronized(o1) {
System.out.println(threadName + "已经进入 o1");
}
}
}
}
public static void main(String[] args)
{
DeadLock dl1 = new DeadLock();
DeadLock dl2 = new DeadLock();
dl1.flag = true;
dl2.flag = false;
new Thread(dl1).start();
new Thread(dl2).start();
}
}