多线程的创建和同步
线程的六种状态
新建(NEW)
至今尚未启动的线程处于这种状态。
可运行(RUNNABLE)
一旦调用start()方法,线程就处于可运行(RUNNABLE)状态。一个可运行的状态可能正在运行也可能没有运行,由操作系统为线程提供具体的运行时间。
终止(TERMINATED)
已退出的线程处于这种状态。
等待(WATING)
当线程等待另一个线程通知调度器出现一个条件时,这个线程会进入等待状态。
计时等待(TIMED_WATING)
等待另一个线程来执行取决于指定等待时间的操作的线程处于这种状态,这一状态一直保持到超时期满或者接收到适当的通知。
阻塞(BLOCKED)
受阻塞并等待某个监视器锁的线程处于这种状态,失去了CPU的执行权
线程的生命周期
线程的创建
继承Thread类
package com.ht.thread;
class demo1 extends Thread{
@Override
public void run() {
super.run();
for(int i = 0; i < 100; i++){
if(i % 2 == 0){
System.out.println(getName() + ": " + i);
}
}
}
}
public class Test {
public static void main(String[] args) {
demo1 d1 = new demo1();
d1.start();
for(int i = 0; i < 100; i++){
if(i % 2 != 0){
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
}
实现Runnable接口
package com.ht.thread;
class demo2 implements Runnable{
@Override
public void run() {
for(int i = 0; i < 100; i++){
if(i % 2 == 0){
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
}
public class Test {
public static void main(String[] args) {
demo2 d2 = new demo2();
Thread t = new Thread(d2);
t.start();
for(int i = 0; i < 100; i++){
if(i % 2 != 0){
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
}
还有一种方法使用lambda表达式
package com.ht.thread;
public class Test {
public static void main(String[] args) {
Runnable r = () -> {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
};
Thread t = new Thread(r);
t.start();
for(int i = 0; i < 100; i++){
if(i % 2 != 0){
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
}
实现Callable接口
Callable接口与Runnable接口的区别
1.call()有返回值,FutureTask类中的get()方法可以获取返回值
2.call()可以抛出异常
3.Callable支持泛型
package com.ht.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
class PrintNumber implements Callable {
@Override
public Object call() throws Exception {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
return null;
}
}
public class CallableTest {
public static void main(String[] args) {
//创建Callable接口实现类的对象
PrintNumber n1 = new PrintNumber();
//将此Callable接口实现类的对象作为传递到FutureTask构造器中,创建FutureTask的对象
FutureTask task = new FutureTask(n1);
//将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()
Thread t = new Thread(task);
t.start();
}
}
使用线程池创建线程
package com.ht.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
class PrintNumber implements Callable {
@Override
public Object call() throws Exception {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
return null;
}
}
public class ThreadPool {
public static void main(String[] args) {
ThreadPoolExecutor service = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
service.submit(new PrintNumber());
service.shutdown();
}
}
使用一下两个方法启动线程,线程使用完需要使用shutdown()方法关闭线程池
线程的同步
同步代码块
synchronized(同步监视器){
//需要同步的代码
}
[同步监视器]:锁。任何一个类的对象都可以充当锁
注意:必须保证多个线程共用同一把锁
继承Thread类的写法
package com.ht.thread;
class Window1 extends Thread{
private static int tickets = 100;
private static Object obj = new Object(); //为了保证使用同一把锁,所以使用static进行修饰,此时对象对类的对象
@Override
public void run() {
while(true){
synchronized(obj) {
if (tickets > 0) {
System.out.println(getName() + "出售车票" + " 票号:" + tickets);
tickets--;
} else {
break;
}
}
}
}
}
public class WindowTest {
public static void main(String[] args) {
Window1 w1 = new Window1();
Window1 w2 = new Window1();
w1.setName("窗口1");
w2.setName("窗口2");
w1.start();
w2.start();
}
}
实现Runnable接口的写法
package com.ht.thread;
class Window2 implements Runnable{
private int tickets = 100;
@Override
public void run() {
while(true){
synchronized(this) {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "出售车票" + " 票号:" + tickets);
tickets--;
} else {
break;
}
}
}
}
}
public class WindowTest2 {
public static void main(String[] args) {
Window2 w = new Window2();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t1.start();
t2.start();
}
}
同步方法
同步方法就是把要同步的代码单独写到一个方法中去,这个方法使用synchronized修饰
继承Thread方法
package com.ht.thread;
class Window1 extends Thread{
private static int tickets = 100;
@Override
public void run() {
while(true){
if(tickets <= 0){
break;
}
show();
}
}
public static synchronized void show(){ //使用static修饰保证是同一把锁
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "出售车票" + " 票号:" + tickets);
tickets--;
}
}
}
public class WindowTest {
public static void main(String[] args) {
Window1 w1 = new Window1();
Window1 w2 = new Window1();
w1.setName("窗口1");
w2.setName("窗口2");
w1.start();
w2.start();
}
}
实现Runnable接口
package com.ht.thread;
class Window2 implements Runnable{
private int tickets = 100;
@Override
public void run() {
while(true){
if(tickets <= 0){
break;
}
show();
}
}
public synchronized void show(){
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "出售车票" + " 票号:" + tickets);
tickets--;
}
}
}
public class WindowTest2 {
public static void main(String[] args) {
Window2 w = new Window2();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
t1.setName("窗口1");
t2.setName("窗口2");
t1.start();
t2.start();
}
}
同步锁
package com.ht.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
class demo4 implements Runnable{
private int num = 100;
private ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try {
lock.lock();
if(num > 0){
Thread.sleep(100);
System.out.println(Thread.currentThread().getName() + ": " + num);
num--;
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
public class Test {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(3);
var d1 = new demo4();
service.execute(d1);
service.execute(d1);
service.execute(d1);
service.shutdown();
}
}
Lock和synchonized的区别
synchronized在执行完相应同步代码后,会自动释放同步监视器
Lock需要手动的启动同步(lock())和结束同步(unlock())