线程的创建,守护线程,线程等待,线程让出,线程同步,线程异步
同步块用的锁(synchronized 里面的参数)必须是同一个对象
package com.kaired.demo;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Demo1 {
public static void main(String[] args) throws InterruptedException {
Thread1 thread1 = new Thread1();
Thread2 thread2 = new Thread2();
Thread thread_1 = new Thread(thread1);
Thread thread_2 = new Thread(thread2);
// 设置线程的优先级
thread_1.setPriority(Thread.MIN_PRIORITY);
thread_2.setPriority(Thread.MAX_PRIORITY);
// 设置后台(守护)线程
thread_1.setDaemon(true);
// 启动1号线程
thread_1.start();
// 启动2号线程
thread_2.start();
// 设置线程等待
thread_1.join();
final Cars cars = new Cars();
// 模拟线程同步错误, 使用同步方法解决
Thread t_car = new Thread() {
@Override
public void run() {
while (true) {
System.out.println(cars.getCar());
}
}
};
Thread t_car2 = new Thread() {
@Override
public void run() {
while (true) {
System.out.println(cars.getCar());
}
}
};
t_car.start();
t_car2.start();
// 模拟线程同步错误,使用同步块解决
Toilet toilet = new Toilet();
Thread to_1 = new Thread() {
@Override
public void run() {
toilet.up();
}
};
Thread to_2 = new Thread() {
@Override
public void run() {
toilet.up();
}
};
to_1.start();
to_2.start();
System.out.println("结束");
}
}
class Thread1 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
}
class Thread2 implements Runnable {
@Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (int i = 0; i < 1; i++) {
try {
Date time = Calendar.getInstance().getTime();
System.out.println(sdf.format(time));
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Cars{
int number = 10;
// 当一个方法被synchronized修饰后,每次只能有一个线程进入该方法
public synchronized int getCar() {
if (number == 0) {
throw new RuntimeException("无车了");
}
// 主动让出线程占用的CPU,此处是为了展现问题加上
Thread.yield();
return number--;
}
}
class Toilet{
public void up() {
String name = Thread.currentThread().getName();
try {
System.out.println("可以同时干" + name);
Thread.sleep(5000);
synchronized (this) {
System.out.println("不可以同时干" + name);
Thread.sleep(5000);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("结束");
}
}