程序、线程和进程
程序 :程序是指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念。进程 :进程是程序的一次执行过程,它是一个动态的概念。是系统资源分配的单位。线程 :一个进程中至少包含一个线程,否则没有存在的意义。线程是CPU执行和调度的单位。
线程是独立的执行路径。 程序运行时,即使没有自己创建线程,后台也有多个线程,比如主线程、gc线程。 main()是主线程,系统的入口,用于执行整个程序。 一个进程中,如果开辟了多个线程,线程的调度由CPU安排调度,CPU与操作系统紧密相关,人为不能干预。 对同一份资源操作时,会存在资源抢夺问题,需要加入并发控制。 线程会带来额外的开销,如并发控制开销,CPU调度开销。 每个线程在自己的工作内存交互,内存不当会造成数据不一致。
Thread
自定义线程继承Thread类 重写run()方法,编写线程执行体 创建线程对象,调用start()方法
public class TestThread01 extends Thread {
@Override
public void run ( ) {
for ( int i = 0 ; i < 200 ; i++ ) {
System. out. println ( "我在看代码---" + i) ;
}
}
public static void main ( String[ ] args) {
TestThread01 testThread01 = new TestThread01 ( ) ;
testThread01. start ( ) ;
for ( int i = 0 ; i < 1000 ; i++ ) {
System. out. println ( "我在学习多线程---" + i) ;
}
}
}
import org. apache. commons. io. FileUtils;
import java. io. File;
import java. io. IOException;
import java. net. URL;
public class TestThread02 extends Thread {
private String url;
private String name;
public TestThread02 ( String name, String url) {
this . url = url;
this . name = name;
}
@Override
public void run ( ) {
WebDownloader webDownloader = new WebDownloader ( ) ;
webDownloader. downloader ( name, url) ;
System. out. println ( "下载的文件名为" + name) ;
}
public static void main ( String[ ] args) {
TestThread02 t1 = new TestThread02 ( "1.jpg" , "图片url" ) ;
TestThread02 t2 = new TestThread02 ( "1.jpg" , "图片url" ) ;
TestThread02 t3 = new TestThread02 ( "1.jpg" , "图片url" ) ;
t1. start ( ) ;
t2. start ( ) ;
t3. start ( ) ;
}
}
class WebDownloader {
public void downloader ( String name, String url) {
try {
FileUtils. copyURLToFile ( new URL ( url) , new File ( name) ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
System. out. println ( "IO异常,downloader方法出现问题" ) ;
}
}
}
实现Runnable接口
定义MyRunnable类实现Runnable接口 实现run()方法,编写线程执行体 创建线程对象,调用start()方法启动线程
推荐使用Runnable接口,因为java单继承的局限性
public class TestThread03 implements Runnable {
@Override
public void run ( ) {
for ( int i = 0 ; i < 200 ; i++ ) {
System. out. println ( "我在看代码---" + i) ;
}
}
public static void main ( String[ ] args) {
TestThread03 testThread03 = new TestThread03 ( ) ;
new Thread ( testThread03) . start ( ) ;
for ( int i = 0 ; i < 1000 ; i++ ) {
System. out. println ( "我在学习多线程---" + i) ;
}
}
}
public class TestThread04 implements Runnable {
private int ticketNum = 10 ;
@Override
public void run ( ) {
while ( true ) {
if ( ticketNum <= 0 ) {
break ;
}
try {
Thread. sleep ( 200 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System. out. println ( Thread. currentThread ( ) . getName ( ) + "-->拿到了第" + ticketNum-- + "票" ) ;
}
}
public static void main ( String[ ] args) {
TestThread04 ticket = new TestThread04 ( ) ;
new Thread ( ticket, "小明" ) . start ( ) ;
new Thread ( ticket, "老师" ) . start ( ) ;
new Thread ( ticket, "黄牛党" ) . start ( ) ;
}
}
public class Race implements Runnable {
private static String winner;
@Override
public void run ( ) {
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( Thread. currentThread ( ) . getName ( ) . equals ( "兔子" ) && i % 10 == 0 ) {
try {
Thread. sleep ( 2 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
boolean flag = gameOver ( i) ;
if ( flag) {
break ;
}
System. out. println ( Thread. currentThread ( ) . getName ( ) + "-->跑了" + i+ "步" ) ;
}
}
private boolean gameOver ( int steps) {
if ( winner != null) {
return true ;
} else {
if ( steps == 100 ) {
winner = Thread. currentThread ( ) . getName ( ) ;
System. out. println ( "winner is " + winner) ;
return false ;
}
}
return false ;
}
public static void main ( String[ ] args) {
Race race = new Race ( ) ;
new Thread ( race, "兔子" ) . start ( ) ;
new Thread ( race, "乌龟" ) . start ( ) ;
}
}
实现callcable接口
实现Runnable接口,需要返回值类型 重写call方法,需要抛出异常 创建目标对象 创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1) 提交执行:Future r1 = ser.submit(t1) 获取结果:boolean rs1 = r1.get() 关闭服务:ser.shutdownNow()
public class TestThread05 implements Callable < Boolean> {
private String url;
private String name;
public TestThread05 ( String name, String url) {
this . url = url;
this . name = name;
}
@Override
public Boolean call ( ) throws Exception {
WebDownloader webDownloader = new WebDownloader ( ) ;
webDownloader. downloader ( name, url) ;
System. out. println ( "下载的文件名为" + name) ;
return true ;
}
public static void main ( String[ ] args) throws ExecutionException, InterruptedException {
TestThread05 t1 = new TestThread05 ( "1.jpg" , "图片url" ) ;
TestThread05 t2 = new TestThread05 ( "1.jpg" , "图片url" ) ;
TestThread05 t3 = new TestThread05 ( "1.jpg" , "图片url" ) ;
ExecutorService ser = Executors. newFixedThreadPool ( 3 ) ;
Future< Boolean> r1 = ser. submit ( t1) ;
Future< Boolean> r2 = ser. submit ( t2) ;
Future< Boolean> r3 = ser. submit ( t3) ;
boolean rs1 = r1. get ( ) ;
boolean rs2 = r2. get ( ) ;
boolean rs3 = r3. get ( ) ;
System. out. println ( rs1) ;
System. out. println ( rs2) ;
System. out. println ( rs3) ;
ser. shutdownNow ( )
}
}
静态代理
真实对象和代理对象实现同一个接口 代理对象代理真实对象
public class StaticProxy {
public static void main ( String[ ] args) {
WeddingCompany weddingCompany = new WeddingCompany ( new You ( ) ) ;
weddingCompany. HappyMarry ( ) ;
}
}
interface Marry {
void HappyMarry ( ) ;
}
class You implements Marry {
@Override
public void HappyMarry ( ) {
System. out. println ( "秦老师要结婚了,超级开心" ) ;
}
}
class WeddingCompany implements Marry {
private Marry target;
public WeddingCompany ( Marry target) {
this . target = target;
}
@Override
public void HappyMarry ( ) {
before ( ) ;
this . target. HappyMarry ( ) ;
after ( ) ;
}
public void before ( ) {
System. out. println ( "结婚之前,布置现场" ) ;
}
public void after ( ) {
System. out. println ( "结婚之后,收尾款" ) ;
}
}
Lambda表达式
public class TestLambda {
static class Like2 implements ILike {
@Override
public void lambda ( ) {
System. out. println ( "I like lambda2" ) ;
}
}
public static void main ( String[ ] args) {
ILike like = new Like ( ) ;
like. lambda ( ) ;
like = new Like2 ( ) ;
like. lambda ( ) ;
class Like3 implements ILike {
@Override
public void lambda ( ) {
System. out. println ( "I like lambda3" ) ;
}
}
like = new Like3 ( ) ;
like. lambda ( ) ;
like = new ILike ( ) {
@Override
public void lambda ( ) {
System. out. println ( "I like lambda3" ) ;
}
} ;
like = ( ) - > {
System. out. println ( "I like lambda4" ) ;
} ;
like. lambda ( ) ;
}
}
interface ILike {
void lambda ( ) ;
}
class Like implements ILike {
@Override
public void lambda ( ) {
System. out. println ( "I like lambda" ) ;
}
}
public class TestLambda2 {
public static void main ( String[ ] args) {
ILove love = null;
love = ( a, b, c) - > {
System. out. println ( a) ;
System. out. println ( b) ;
} ;
love. love ( 501 , 502 , 503 ) ;
}
}
interface ILove {
void love ( int a, int b, int c) ;
}
线程状态
public class TestStop implements Runnable {
private boolean flag = true ;
@Override
public void run ( ) {
int i = 0 ;
while ( flag) {
System. out. println ( "run...Thread" + i++ ) ;
}
}
public void stop ( ) {
this . flag = false ;
}
public static void main ( String[ ] args) {
TestStop testStop = new TestStop ( ) ;
new Thread ( testStop) . start ( ) ;
for ( int i = 0 ; i < 1000 ; i++ ) {
System. out. println ( "main" + i) ;
if ( i== 900 ) {
testStop. stop ( ) ;
System. out. println ( "线程该停止了" ) ;
}
}
}
}
线程休眠
sleep(时间)指定当前线程阻塞的毫秒数 sleep存在异常InterruptedException sleep时间达到后线程进入就绪状态 sleep可以模拟网络延时,倒计时等 每一个对象都有一个锁,sleep对象不会释放锁
public class TestSleep {
public static void main ( String[ ] args) {
try {
tenDown ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
public static void tenDown ( ) throws InterruptedException {
int num = 10 ;
while ( true ) {
Thread. sleep ( 1000 ) ;
System. out. println ( num-- ) ;
if ( num <= 0 ) {
break ;
}
}
}
}
线程礼让
让当前正在执行线程暂停,但不阻塞 将线程从运行状态转为就绪状态 让cpu重新调度,礼让不一定成功,看cpu心情
public static void main ( String[ ] args) {
MyYield myYield = new MyYield ( ) ;
new Thread ( myYield, "a" ) . start ( ) ;
new Thread ( myYield, "b" ) . start ( ) ;
}
}
class MyYield implements Runnable {
@Override
public void run ( ) {
System. out. println ( Thread. currentThread ( ) . getName ( ) + "线程开始执行" ) ;
Thread. yield ( ) ;
System. out. println ( Thread. currentThread ( ) . getName ( ) + "线程结束执行" ) ;
}
}
Join
Join合并线程,待此线程完成之后,再执行其他线程,其他线程阻塞 可以想象成插队
public class TestJoin implements Runnable {
@Override
public void run ( ) {
for ( int i = 0 ; i < 1000 ; i++ ) {
System. out. println ( "线程VIP来了" + i) ;
}
}
public static void main ( String[ ] args) throws InterruptedException {
TestJoin testJoin = new TestJoin ( ) ;
Thread thread = new Thread ( testJoin) ;
thread. start ( ) ;
for ( int i = 0 ; i < 200 ; i++ ) {
if ( i== 200 ) {
thread. join ( ) ;
}
}
}
}
线程状态
public class TestState {
public static void main ( String[ ] args) throws InterruptedException {
Thread thread = new Thread ( ( ) - > {
for ( int i = 0 ; i < 5 ; i++ ) {
try {
Thread. sleep ( 1000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
System. out. println ( "///" ) ;
} ) ;
Thread. State state = thread. getState ( ) ;
System. out. println ( state) ;
thread. start ( ) ;
state = thread. getState ( ) ;
System. out. println ( state) ;
while ( state != Thread. State. TERMINATED) {
Thread. sleep ( 100 ) ;
state = thread. getState ( ) ;
System. out. println ( state) ;
}
}
}
线程优先级(优先级低只是意味着获得调度的概率低)
public class TestPriority {
public static void main ( String[ ] args) {
System. out. println ( Thread. currentThread ( ) . getName ( ) + "-->" + Thread. currentThread ( ) . getPriority ( ) ) ;
MyPriority myPriority = new MyPriority ( ) ;
Thread t1 = new Thread ( myPriority) ;
Thread t2 = new Thread ( myPriority) ;
Thread t3 = new Thread ( myPriority) ;
Thread t4 = new Thread ( myPriority) ;
t1. start ( ) ;
t2. setPriority ( 1 ) ;
t2. start ( ) ;
t3. setPriority ( 4 ) ;
t3. start ( ) ;
t4. setPriority ( Thread. MAX_PRIORITY) ;
t4. start ( ) ;
}
}
class MyPriority implements Runnable {
@Override
public void run ( ) {
System. out. println ( Thread. currentThread ( ) . getName ( ) + "-->" + Thread. currentThread ( ) . getPriority ( ) ) ;
}
}
守护线程
线程分为守护线程和用户线程 虚拟机必须确保用户线程执行完毕 虚拟机不用等待守护线程执行完毕 如,后台操作数据库,监控内存,垃圾回收等等
public class TestDaemon {
public static void main ( String[ ] args) {
God god = new God ( ) ;
You2 you2 = new You2 ( ) ;
Thread thread = new Thread ( god) ;
thread. setDaemon ( true ) ;
thread. start ( ) ;
new Thread ( you2) . start ( ) ;
}
}
class God implements Runnable {
@Override
public void run ( ) {
while ( true ) {
System. out. println ( "上帝保佑着你" ) ;
}
}
}
class You2 implements Runnable {
@Override
public void run ( ) {
for ( int i = 0 ; i < 36500 ; i++ ) {
System. out. println ( "你一生都开心的活着" ) ;
}
System. out. println ( "======goodBye World" ) ;
}
}
线程同步
线程同步其实是一种等待机制,多个需要同时访问此对象的线程进入对象的等待池形成队列,等待前面一个线程使用完毕,下一个线程再使用。
三大线程不安全案例
public class UnsafeByTicket {
public static void main ( String[ ] args) {
BuyTicket buyTicket = new BuyTicket ( ) ;
new Thread ( buyTicket, "苦逼的我" ) . start ( ) ;
new Thread ( buyTicket, "牛逼的你们" ) . start ( ) ;
new Thread ( buyTicket, "可恶的黄牛党" ) . start ( ) ;
}
}
class BuyTicket implements Runnable {
private int ticketNums = 10 ;
boolean flag = true ;
@Override
public void run ( ) {
while ( flag) {
try {
buy ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
}
private void buy ( ) throws InterruptedException {
if ( ticketNums <= 0 ) {
flag = false ;
return ;
}
Thread. sleep ( 100 ) ;
System. out. println ( Thread. currentThread ( ) . getName ( ) + "拿到" + ticketNums-- ) ;
}
}
public class UnsafeBank {
public static void main ( String[ ] args) {
Account account = new Account ( 100 , "结婚基金" ) ;
Drawing you = new Drawing ( account, 50 , "你" ) ;
Drawing girlfriend = new Drawing ( account, 100 , "girlfriend" ) ;
you. start ( ) ;
girlfriend. start ( ) ;
}
}
class Account {
int money;
String name;
public Account ( int money, String name) {
this . money = money;
this . name = name;
}
}
class Drawing extends Thread {
Account account;
int drawingMoney;
int nowMoney;
public Drawing ( Account account, int drawingMoney, String name) {
super ( name) ;
this . account = account;
this . drawingMoney = drawingMoney;
}
@Override
public void run ( ) {
if ( account. money - drawingMoney < 0 ) {
System. out. println ( Thread. currentThread ( ) . getName ( ) + "钱不够,取不了" ) ;
return ;
}
try {
Thread. sleep ( 100 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
account. money = account. money - drawingMoney;
nowMoney = nowMoney + drawingMoney;
System. out. println ( account. name + "余额为:" + account. money) ;
System. out. println ( this . getName ( ) + "手里的钱:" + nowMoney) ;
}
}
import java. util. ArrayList;
import java. util. List;
public class UnsafeList {
public static void main ( String[ ] args) {
List< String> list = new ArrayList < > ( ) ;
for ( int i = 0 ; i < 10000 ; i++ ) {
new Thread ( ( ) - > {
list. add ( Thread. currentThread ( ) . getName ( ) ) ;
} ) . start ( ) ;
}
try {
Thread. sleep ( 300 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System. out. println ( list. size ( ) ) ;
}
}
同步方法和同步块
public class UnsafeByTicket {
public static void main ( String[ ] args) {
BuyTicket buyTicket = new BuyTicket ( ) ;
new Thread ( buyTicket, "苦逼的我" ) . start ( ) ;
new Thread ( buyTicket, "牛逼的你们" ) . start ( ) ;
new Thread ( buyTicket, "可恶的黄牛党" ) . start ( ) ;
}
}
class BuyTicket implements Runnable {
private int ticketNums = 10 ;
boolean flag = true ;
@Override
public void run ( ) {
while ( flag) {
try {
buy ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
}
private synchronized void buy ( ) throws InterruptedException {
if ( ticketNums <= 0 ) {
flag = false ;
return ;
}
Thread. sleep ( 100 ) ;
System. out. println ( Thread. currentThread ( ) . getName ( ) + "拿到" + ticketNums-- ) ;
}
}
public class UnsafeBank {
public static void main ( String[ ] args) {
Account account = new Account ( 100 , "结婚基金" ) ;
Drawing you = new Drawing ( account, 50 , "你" ) ;
Drawing girlfriend = new Drawing ( account, 100 , "girlfriend" ) ;
you. start ( ) ;
girlfriend. start ( ) ;
}
}
class Account {
int money;
String name;
public Account ( int money, String name) {
this . money = money;
this . name = name;
}
}
class Drawing extends Thread {
Account account;
int drawingMoney;
int nowMoney;
public Drawing ( Account account, int drawingMoney, String name) {
super ( name) ;
this . account = account;
this . drawingMoney = drawingMoney;
}
@Override
public void run ( ) {
synchronized ( account) {
if ( account. money - drawingMoney < 0 ) {
System. out. println ( Thread. currentThread ( ) . getName ( ) + "钱不够,取不了" ) ;
return ;
}
try {
Thread. sleep ( 100 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
account. money = account. money - drawingMoney;
nowMoney = nowMoney + drawingMoney;
System. out. println ( account. name + "余额为:" + account. money) ;
System. out. println ( this . getName ( ) + "手里的钱:" + nowMoney) ;
}
}
}
import java. util. ArrayList;
import java. util. List;
public class UnsafeList {
public static void main ( String[ ] args) {
List< String> list = new ArrayList < > ( ) ;
for ( int i = 0 ; i < 10000 ; i++ ) {
new Thread ( ( ) - > {
synchronized ( list) {
list. add ( Thread. currentThread ( ) . getName ( ) ) ;
}
} ) . start ( ) ;
}
try {
Thread. sleep ( 300 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System. out. println ( list. size ( ) ) ;
}
}
测试JUC安全类型的集合
public class TestJUC {
public static void main ( String[ ] args) {
CopyOnWriteArrayList< String> list = new CopyOnWriteArrayList < > ( ) ;
for ( int i = 0 ; i < 10000 ; i++ ) {
new Thread ( ( ) - > {
list. add ( Thread. currentThread ( ) . getName ( ) ) ;
} ) . start ( ) ;
}
try {
Thread. sleep ( 3000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System. out. println ( list. size ( ) ) ;
}
}
死锁
多个线程各自占有一公共资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止的情形。某个同步块拥有"两个以上对象的锁"时,就可能发生死锁的问题。
public class DeadLock {
public static void main ( String[ ] args) {
Makeup g1 = new Makeup ( 0 , "灰姑娘" ) ;
Makeup g2 = new Makeup ( 1 , "白雪公主" ) ;
g1. start ( ) ;
g2. start ( ) ;
}
}
class LipsTick {
}
class Mirror {
}
class Makeup extends Thread {
static LipsTick lipsTick = new LipsTick ( ) ;
static Mirror mirror = new Mirror ( ) ;
int choice;
String girlName;
Makeup ( int choice, String girlName) {
this . choice = choice;
this . girlName = girlName;
}
@Override
public void run ( ) {
try {
makeup ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
private void makeup ( ) throws InterruptedException {
if ( choice == 0 ) {
synchronized ( lipsTick) {
System. out. println ( this . girlName+ "获得口红的锁" ) ;
Thread. sleep ( 1000 ) ;
synchronized ( mirror) {
System. out. println ( this . girlName+ "获得镜子的锁" ) ;
}
}
} else {
synchronized ( mirror) {
System. out. println ( this . girlName+ "获得镜子的锁" ) ;
Thread. sleep ( 1000 ) ;
synchronized ( lipsTick) {
System. out. println ( this . girlName+ "获得口红的锁" ) ;
}
}
}
}
}
产生死锁的四个必要条件
互斥条件:一个资源一次只能被一个进程使用 请求与保持条件:一个进程因请求的资源而阻塞时,对以获得的资源保持不放 不剥夺条件:进程已获得的资源,在执行完成之前,不能强行剥夺 循环等待条件:若干进程之间形成一种头尾相连的循环等待资源关系
Lock锁
通过显示定义同步锁对象来实现同步。同步锁用Lock对象充当。
public class TestLock {
public static void main ( String[ ] args) {
TestLock2 testLock2 = new TestLock2 ( ) ;
new Thread ( testLock2) . start ( ) ;
new Thread ( testLock2) . start ( ) ;
new Thread ( testLock2) . start ( ) ;
}
}
class TestLock2 implements Runnable {
int ticketNums = 10 ;
private final ReentrantLock lock = new ReentrantLock ( ) ;
@Override
public void run ( ) {
while ( true ) {
try {
lock. lock ( ) ;
if ( ticketNums > 0 ) {
try {
Thread. sleep ( 1000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System. out. println ( ticketNums-- ) ;
} else {
break ;
}
} finally {
lock. unlock ( ) ;
}
}
}
}
生产者消费者问题
public class TestPC {
public static void main ( String[ ] args) {
SynContainer synContainer = new SynContainer ( ) ;
new Productor ( synContainer) . start ( ) ;
new Consumer ( synContainer) . start ( ) ;
}
}
class Productor extends Thread {
SynContainer synContainer;
public Productor ( SynContainer synContainer) {
this . synContainer = synContainer;
}
@Override
public void run ( ) {
for ( int i = 0 ; i < 100 ; i++ ) {
synContainer. push ( new Chicken ( i) ) ;
System. out. println ( "生产了" + i + "鸡" ) ;
}
}
}
class Consumer extends Thread {
SynContainer synContainer;
public Consumer ( SynContainer synContainer) {
this . synContainer = synContainer;
}
@Override
public void run ( ) {
for ( int i = 0 ; i < 100 ; i++ ) {
synContainer. pop ( ) ;
System. out. println ( "消费了" + i + "鸡" ) ;
}
}
}
class Chicken {
int id;
public Chicken ( int id) {
this . id = id;
}
}
class SynContainer {
Chicken[ ] chickens = new Chicken [ 10 ] ;
int count = 0 ;
public synchronized void push ( Chicken chicken) {
if ( count == chickens. length) {
try {
this . wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
chickens[ count] = chicken;
count++ ;
this . notify ( ) ;
}
public synchronized Chicken pop ( ) {
if ( count == 0 ) {
try {
this . wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
count-- ;
Chicken chicken = chickens[ count] ;
this . notify ( ) ;
return chicken;
}
}
public class TestPC2 {
public static void main ( String[ ] args) {
TV tv = new TV ( ) ;
new Player ( tv) . start ( ) ;
new Watcher ( tv) . start ( ) ;
}
}
class Player extends Thread {
TV tv;
public Player ( TV tv) {
this . tv = tv;
}
@Override
public void run ( ) {
for ( int i = 0 ; i < 20 ; i++ ) {
if ( i% 2 == 0 ) {
this . tv. play ( "快乐大本营播放中" ) ;
} else {
this . tv. play ( "抖音:记录美好生活" ) ;
}
}
}
}
class Watcher extends Thread {
TV tv;
public Watcher ( TV tv) {
this . tv = tv;
}
@Override
public void run ( ) {
for ( int i = 0 ; i < 20 ; i++ ) {
tv. watch ( ) ;
}
}
}
class TV {
String voice;
boolean flag = true ;
public synchronized void play ( String voice) {
System. out. println ( "演员表演了:" + voice) ;
this . notifyAll ( ) ;
this . voice = voice;
this . flag = ! this . flag;
}
public synchronized void watch ( ) {
if ( flag) {
try {
this . wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
System. out. println ( "观看了:" + voice) ;
this . notifyAll ( ) ;
this . flag = ! this . flag;
}
}
使用线程池
背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。 思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中,可以避免频繁创建销毁。实现重复利用。 好处:提高响应速度,降低资源消耗,便于线程管理。
import java. util. concurrent. ExecutorService;
import java. util. concurrent. Executors;
public class TestPool {
public static void main ( String[ ] args) {
ExecutorService service = Executors. newFixedThreadPool ( 10 ) ;
service. execute ( new MyThread ( ) ) ;
service. execute ( new MyThread ( ) ) ;
service. execute ( new MyThread ( ) ) ;
service. execute ( new MyThread ( ) ) ;
service. shutdown ( ) ;
}
}
class MyThread implements Runnable {
@Override
public void run ( ) {
System. out. println ( Thread. currentThread ( ) . getName ( ) ) ;
}
}
总结
import java. util. concurrent. Callable;
import java. util. concurrent. ExecutionException;
import java. util. concurrent. FutureTask;
public class ThreadNew {
public static void main ( String[ ] args) {
new Thread1 ( ) . start ( ) ;
new Thread ( new Thread2 ( ) ) . start ( ) ;
FutureTask< Integer> futureTask = new FutureTask < Integer> ( new Thread3 ( ) ) ;
new Thread ( futureTask) . start ( ) ;
try {
Integer i = futureTask. get ( ) ;
System. out. println ( i) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
} catch ( ExecutionException e) {
e. printStackTrace ( ) ;
}
}
}
class Thread1 extends Thread {
@Override
public void run ( ) {
System. out. println ( "Thread1" ) ;
}
}
class Thread2 implements Runnable {
@Override
public void run ( ) {
System. out. println ( "Thread2" ) ;
}
}
class Thread3 implements Callable < Integer> {
@Override
public Integer call ( ) throws Exception {
System. out. println ( "Thread3" ) ;
return 100 ;
}
}