在Java中主要提供两种方式实现线程,分别为继承java.lang.Thread类与实现java.lang.Runnable接口。
public class ThreadTest extends Thread {
private int count = 10;
@Override
public void run() { // 重写run()方法
while (true) {
System.out.print(count + " "); // 打印count变量
if (--count == 0) { // 使count变量自减,当自减为0时,退出循环
return;
}
}
}
public static void main(String[] args) {
new ThreadTest().start();
}
}
如果start()方法调用一个已经启动的线程,系统将抛出IllegalThreadStateException异常。
public class ThreadTest extends Thread {
private int count = 10;
@Override
public void run() { // 重写run()方法
while (true) {
System.out.print(count + " "); // 打印count变量
if (--count == 0) {
return;
}
}
}
public static void main(String[] args) {
ThreadTest t = new ThreadTest();
t.start();
int a = Thread.MIN_PRIORITY;
try {
t.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
线程安全
public class ThreadSafeTest implements Runnable {
int num = 10;
@Override
public void run() {
while (true) {
if (num > 0) {
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("tickets" + num--);
}
}
}
public static void main(String[] args) {
ThreadSafeTest t = new ThreadSafeTest(); // 实例化类对象
Thread tA = new Thread(t); // 以该类对象分别实例化4个线程
Thread tB = new Thread(t);
Thread tC = new Thread(t);
Thread tD = new Thread(t);
tA.start(); // 分别启动线程
tB.start();
tC.start();
tD.start();
}
}
线程同步机制
1.同步块
public class ThreadSynchronizedTest implements Runnable {
int num = 10;
@Override
public void run() {
while (true) {
synchronized ("") {
if (num > 0) {
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("tickets" + num--);
}
}
}
}
public static void main(String[] args) {
ThreadSynchronizedTest t = new ThreadSynchronizedTest(); // 实例化类对象
Thread tA = new Thread(t); // 以该类对象分别实例化4个线程
Thread tB = new Thread(t);
Thread tC = new Thread(t);
Thread tD = new Thread(t);
tA.start(); // 分别启动线程
tB.start();
tC.start();
tD.start();
}
}
public class ThreadSynchronizedTest implements Runnable {
int num = 10;
public synchronized void doSynchronization() { // 定义同步方法
if (num > 0) {
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("tickets" + num--);
}
}
@Override
public void run() {
while (true) {
doSynchronization();
}
}
public static void main(String[] args) {
ThreadSynchronizedTest t = new ThreadSynchronizedTest(); // 实例化类对象
Thread tA = new Thread(t); // 以该类对象分别实例化4个线程
Thread tB = new Thread(t);
Thread tC = new Thread(t);
Thread tD = new Thread(t);
tA.start(); // 分别启动线程
tB.start();
tC.start();
tD.start();
}
}