一、程序 进程 线程
1、程序:指令集 静态概念
2、进程:操作系统 调度程序 动态概念
3、线程:在进程内多条执行路径
thread的缺点是Java只能单继承
静态代理模式
/**
* 静态代理 设计模式
* 1、真实角色
* 2、代理角色
* 3、实现同一个接口
*/
public class StaticProxy {
}
interface Marray{
public abstract void marray();
}
class You implements Marray{
@Override
public void marray() {
System.out.println("you and wife marray...");
}
}
class WeddingCompany implements Marray{
private Marray you;
public WeddingCompany() {
}
public WeddingCompany(Marray you) {
this.you = you;
}
private void before(){
System.out.println("布置场地。。。");
}
private void after(){
System.out.println("闹洞房。。。");
}
@Override
public void marray() {
before();
you.marray();
after();
}
public static void main(String[] args) {
Marray you=new You();
WeddingCompany company=new WeddingCompany(you);
company.marray();
}
}
实现Runnable接口
/**
* 1、避免单继承局限性
* 2、方便共享资源
* 使用Runnable创建线程
* 1、类 实现Runnable接口 +重写run() -->真实角色
* 2、启动多线程 使用静态代理
* 1)、创建真实角色
* 2)、创建代理角色+真实角色引用
* 3)、调用.start() 启动线程
*/
public class Programer implements Runnable{
@Override
public void run() {
for(int i=0;i<1000;i++){
System.out.println("I am a programer我在敲代码。。");
}
}
}
public class ProgramerApp {
public static void main(String[] args) {
//创建真实角色
Programer pro=new Programer();
//创建代理角色+真实角色引用
Thread proxy=new Thread(pro);
//调用
proxy.start();
for(int i=0;i<1000;i++){
System.out.println("I am a programer我在聊QQ。。");
}
}
}
/**
* 方便共享资源
*/
public class Station implements Runnable{
private int tickets=50;
@Override
public void run() {
while(true){
if(tickets<0){
break;
}
System.out.println(Thread.currentThread().getName()+"拿到票"+tickets--);
}
}
public static void main(String[] args) {
//真实角色
Station station=new Station();
//三个静态代理
Thread t1=new Thread(station,"A");
Thread t2=new Thread(station,"B");
Thread t3=new Thread(station,"C");
t1.start();
t2.start();
t3.start();
}
}
实现Callable接口创建线程
import java.util.concurrent.*;
/**
*使用Callable创建线程
*/
public class Call {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建线程
ExecutorService ser=Executors.newFixedThreadPool(2);
Race tor=new Race("乌龟",1000);
Race rabbit=new Race("兔子",500);
//获取值
Future<Integer> result=ser.submit(tor);
Future<Integer> result2=ser.submit(rabbit);
Thread.sleep(5000);
tor.setFlag(false);
rabbit.setFlag(false);
int num1=result.get();
int num2=result2.get();
System.out.println("乌龟跑了"+num1+"步");
System.out.println("兔子跑了"+num2+"步");
//停止服务
ser.shutdownNow();
}
}
class Race implements Callable<Integer> {
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public int getStep() {
return step;
}
public void setStep(int step) {
this.step = step;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
private long time;
private int step = 0;
private boolean flag = true;
public Race(String name, long time) {
this.name = name;
this.time = time;
}
@Override
public Integer call() throws Exception {
while(flag){
Thread.sleep(time);
step++;
}
return step;
}
}
线程状态
1、新生状态
2、就绪状态
3、运行状态
4、就绪状态
5、死亡状态
二、停止线程
1、自然终止:线程体正常执行完毕
2、外部干涉:
1)、线程类中定义线程体使用的标识
2)、线程体使用该标识
3)、提供对外的方法改变该标识
4)、外部根据条件调用该方法即可
三、阻塞
1、join:合并线程
2、yield:暂停自己的线程
3、sleep:休眠,不释放锁
1)、与时间相关:倒计时
2)、模拟网络延时
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 倒计时
*/
public class SleepDemo01 {
public static void main(String[] args) throws InterruptedException {
// int num=10;
// while(true){
// System.out.println(num--);
// Thread.sleep(1000);
// if(num<=0){
// break;
// }
// }
Date endTime=new Date(System.currentTimeMillis()+10*1000);
long end=endTime.getTime();
DateFormat format=new SimpleDateFormat("mm:ss");
while(true){
System.out.println(format.format(endTime));
Thread.sleep(1000);
endTime=new Date(endTime.getTime()+1000);
if(end+10000<endTime.getTime()){
break;
}
}
}
}
/**
* 线程未加锁出现的问题
*/
public class SleepDemo02 implements Runnable{
private int ticket=20;
@Override
public void run() {
while(true){
if(ticket<0){
break;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到票"+ticket--);
}
}
public static void main(String[] args) {
//真实角色
SleepDemo02 station=new SleepDemo02();
//三个静态代理
Thread t1=new Thread(station,"aaa");
Thread t2=new Thread(station,"bbb");
Thread t3=new Thread(station,"ccc");
t1.start();
t2.start();
t3.start();
}
}
线程优先级
public class MyThread implements Runnable {
private boolean flag=true;
private int num=0;
@Override
public void run() {
while(flag){
System.out.println(Thread.currentThread().getName()+" "+num++);
}
}
public void stop(){
this.flag=false;
}
}
/**
* Thread.currentThread()//当前线程
* setName()
* getName()
* isAlive()
*/
public class InfoDemo01 {
public static void main(String[] args) throws InterruptedException {
MyThread thread=new MyThread();
Thread thread1=new Thread(thread,"it");
thread1.setName("zhang");
System.out.println(thread1.getName());
System.out.println(Thread.currentThread().getName());//main线程
thread1.start();
System.out.println("启动后的状态:"+thread1.isAlive());
Thread.sleep(200);
thread.stop();
Thread.sleep(200);
System.out.println("停止后的状态:"+thread1.isAlive());
}
}
/**
* 优先级
* MAX_PRIORITY 10
* MIN_PRIORITY 5(默认)
* NORM_PRIOROTY 1
*/
public class InfoDemo02{
public static void main(String[] args) throws InterruptedException {
MyThread myThread=new MyThread();
Thread thread1=new Thread(myThread,"t1");
Thread thread2=new Thread(myThread,"t2");
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MIN_PRIORITY);
thread1.start();
thread2.start();
Thread.sleep(2000);
myThread.stop();
}
}
线程安全synconize
/**
* 线程安全 synchronized
*/
public class SynThread01 implements Runnable {
private int tickets=10;
private boolean flag=true;
@Override
public void run() {
while(flag){
try {
test6();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//线程不安全
public void test6() throws InterruptedException {
if(tickets<=0){
flag=false;
return ;
}
synchronized (this){
Thread.sleep(500);//模拟延迟
System.out.println(Thread.currentThread().getName()+"拿到票-->"+tickets--);
}
}
//线程不安全 锁定资源不正确
public void test5() throws InterruptedException {
synchronized ((Integer)tickets){
if(tickets<=0){
flag=false;
return ;
}
Thread.sleep(500);//模拟延迟
System.out.println(Thread.currentThread().getName()+"拿到票-->"+tickets--);
}
}
//锁定范围不正确
public void test4() throws InterruptedException {
synchronized (this){
if(tickets<=0){
flag=false;
return ;
}
}
Thread.sleep(500);//模拟延迟
System.out.println(Thread.currentThread().getName()+"拿到票-->"+tickets--);
}
//线程安全 同步块
public void test3() throws InterruptedException {
synchronized (this){
if(tickets<=0){
flag=false;
return ;
}
Thread.sleep(500);//模拟延迟
System.out.println(Thread.currentThread().getName()+"拿到票-->"+tickets--);
}
}
//线程安全 同步方法
public synchronized void test2() throws InterruptedException {
if(tickets<=0){
flag=false;
return;//一定要返回,不然继续执行
}
Thread.sleep(500);
System.out.println(Thread.currentThread().getName()+"拿到票-->"+tickets--);
}
//线程不安全
public void test1() throws InterruptedException {
if(tickets<0){
flag=false;
}
Thread.sleep(500);
System.out.println(Thread.currentThread().getName()+"拿到票-->"+tickets--);
}
public static void main(String[] args) {
//真实角色
SynThread01 station=new SynThread01();
//三个静态代理
Thread t1=new Thread(station,"A");
Thread t2=new Thread(station,"B");
Thread t3=new Thread(station,"C");
t1.start();
t2.start();
t3.start();
}
}
单例模式 (runtime就是一个单例模式)
/**
* 单例设计模式:确保一个类只有一个对象
*/
public class SynThread02 {
public static void main(String[] args) {
JvmThread thread=new JvmThread(500);
JvmThread thread1=new JvmThread(200);
thread.start();
thread1.start();
}
}
class JvmThread extends Thread{
private long time;
public JvmThread(long time) {
this.time = time;
}
public JvmThread() {
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->创建"+Jvm.getInstanse4(time));
}
}
/**
* 单例设计模式
* 一个类只有一个对象
* 懒汉式
* 1、构造器私有化
* 2、声明一个私有静态变量
* 3、创建一个对外的公共的静态方法访问该变量,如果变量没有对象,创建该对象
*/
class Jvm{
//声明一个私有的静态变量
private static Jvm instanse=null;//懒汉式
//构造器私有化、
private Jvm(){
}
//创建一个对外的公共的静态方法访问该变量,如果变量没有对象,创建该对象
public static Jvm getInstanse(long time){
if(null==instanse){
try {
Thread.sleep(time);//延时,放大错误概率
} catch (InterruptedException e) {
e.printStackTrace();
}
instanse=new Jvm();
}
return instanse;
}
public synchronized static Jvm getInstanse2(long time){
if(null==instanse){
try {
Thread.sleep(time);//延时,放大错误概率
} catch (InterruptedException e) {
e.printStackTrace();
}
instanse=new Jvm();
}
return instanse;
}
public static Jvm getInstanse3(long time){
synchronized(Jvm.class){
if(null==instanse){
try {
Thread.sleep(time);//延时,放大错误概率
} catch (InterruptedException e) {
e.printStackTrace();
}
instanse=new Jvm();
}
return instanse;
}
}
public static Jvm getInstanse4(long time){
if(null==instanse){//提高效率
synchronized(Jvm.class){
if(null==instanse){
try {
Thread.sleep(time);//延时,放大错误概率
} catch (InterruptedException e) {
e.printStackTrace();
}
instanse=new Jvm();
}
}
}
return instanse;
}
}
/**
* 饿汉式
* 1、构造器私有化
* 2、声明一个私有静态变量 ,同时创建该对象
* 3、对外提供访问属性的静态方法
*/
class MyJvm2{
private static MyJvm2 instance=new MyJvm2();
private MyJvm2(){}
public MyJvm2 getInstance(){
return instance;
}
}
/**
* 类在使用时才加载,提高加载速度
*/
class MyJvm3{
private static class JvmHolder{
private static MyJvm3 instance=new MyJvm3();
}
private MyJvm3(){}
public static MyJvm3 getInstance(){
return JvmHolder.instance;
}
}
死锁:过多的同步容易造成自锁,多个线程访问同一资源
/**
* 死锁问题
*/
public class DeadSyn {
public static void main(String[] args) {
Object g=new Object();
Object m=new Object();
Test test=new Test(g,m);
Test2 test1=new Test2(g,m);
Thread thread=new Thread(test);
Thread thread2=new Thread(test1);
thread.start();
thread2.start();
}
}
class Test implements Runnable{
Object goods=null;
Object money=null;
public Test(Object goods,Object money) {
this.goods = goods;
this.money=money;
}
@Override
public void run() {
while(true){
test();
}
}
public void test(){
synchronized (goods){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (money){
}
System.out.println("一手交钱");
}
}
}
class Test2 implements Runnable{
Object goods=null;
Object money=null;
public Test2(Object goods,Object money) {
this.goods = goods;
this.money=money;
}
@Override
public void run() {
while(true){
test();
}
}
public void test(){
synchronized (money){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (goods){
}
System.out.println("一手交货");
}
}
}
生产者消费者模式(解决死锁问题)
/**
*一个场景
*/
public class Moive {
private boolean flag=true;
private String string;
//flag-->true 开始你的表演
//flag-->false 观看表演
public synchronized void play(String string) {
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.string=string;
System.out.println("表演者表演了: "+string);
flag=false;
this.notify();
}
public synchronized void watch(){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("观众看到: "+string);
flag=true;
this.notify();
}
}
/**
* 生产者
*/
public class Player implements Runnable{
private Moive m;
public Player(Moive m){
super();
this.m=m;
}
@Override
public void run() {
for(int i=0;i<5;i++){
if(0==i%2){
m.play("左转传");
}else{
m.play("右转转");
}
}
}
}
/**
* 消费者
*/
public class Watcher implements Runnable{
private Moive m;
public Watcher(Moive m){
super();
this.m=m;
}
@Override
public void run() {
for(int i=0;i<5;i++){
if(0==i%2){
m.watch();
}else{
m.watch();
}
}
}
}
public class App {
public static void main(String[] args) {
Moive m=new Moive();
Player player=new Player(m);
Watcher watcher=new Watcher(m);
Thread thread=new Thread(player);
Thread thread1=new Thread(watcher);
thread.start();
thread1.start();
}
}
任务调度
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimerDemo {
public static void main(String[] args) {
Timer timer=new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("哈哈哈。。。");
}
},new Date(System.currentTimeMillis()+1000),500);
}
}
quartz
(开源项目)
编辑
Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它可以与J2EE与J2SE应用程序相结合也可以单独使用。Quartz可以用来创建简单或为运行十个,百个,甚至是好几万个Jobs这样复杂的程序。Jobs可以做成标准的Java组件或 EJBs。Quartz的最新版本为Quartz 2.3.0。