线程的开启
class MyThread extends Thread {
private int ticket = 5;
@Override
public void run() {
}
}
public class MyLearn {
public static void main(String[] args) throws Exception {
MyThread mt1 = new MyThread();
mt1.start();
MyThread mt2 = new MyThread();
mt2.start();
}
}
- 实现Runnable接口,实现run()方法
- 静态代理模式:
- Thread和MyThread都实现Runnable接口
- Thread作为代理,包含MyThread的引用
- 严格的代理设计模式之中应该是调用Thread.run(),而此处调用start()
- 方便表示数据共享的概念
public class MyLearn {
public static void main(String[] args) throws Exception {
MyThread mt1 = new MyThread();
new Thread(mt1).start();
MyThread mt2 = new MyThread();
new Thread(mt2).start();
}
}
class MyThread implements Runnable {
private int ticket = 5;
@Override
public void run() {
}
}
- 实现Callable接口,重写call()方法
- 优点:call()方法可以抛异常并且可以带返回值,run()不可以
class MyThread implements Callable<String> {
@Override
public String call() throws Exception {
Thread.sleep(2000);
return "hello";
}
}
public class MyLearn {
public static void main(String[] args) throws Exception {
ExecutorService threadpool=Executors.newFixedThreadPool(1);
Future<String> future = threadpool.submit(new MyThread());
String s = future.get();
System.out.println(s);
threadpool.shutdown();
}
}
线程的停止
- stop() suspend()方法 已过时
- 标志位
- volatile关键字:解决线程私有堆栈中数据和公共堆栈中的数据不同步
![这里写图片描述](https://i-blog.csdnimg.cn/blog_migrate/a894a7320370820b28368b7c2ce0b729.png)
public class MyLearn {
public static void main(String[] args) throws Exception {
MyThread mt1 = new MyThread();
Thread thread = new Thread(mt1);
thread.start();
Thread.sleep(2000);
mt1.stop();
}
}
class MyThread implements Runnable {
private int ticket = 5;
private volatile boolean flag=true;
public void stop(){
flag=false;
}
@Override
public void run() {
while(flag){
}
System.out.println("run end");
}
}
- 中断线程
- 当线程处于阻塞态,标志位方法不好用,可以interrup()打破阻塞
- public static boolean interrupted() 测试当前线程是否中断并清除中断状态
- public boolean isInterrupted() 测试线程是否中断,不影响线程的状态;
public class MyLearn {
public static void main(String[] args) throws Exception {
MyThread mt1 = new MyThread();
Thread thread = new Thread(mt1);
thread.start();
int num = 0;
while (true) {
Thread.sleep(500);
num++;
if ( num== 3) {
mt1.setFlag(false);
thread.interrupt();
break;
}
}
}
}
class MyThread implements Runnable {
private int ticket = 5;
private volatile boolean flag = true;
public void setFlag(boolean f){
this.flag=f;
}
@Override
public void run() {
while (flag) {
try {
Thread.sleep(3500);
} catch (InterruptedException e) {
System.out.println("over");
}
}
}
}
class MyThread implements Runnable {
private int ticket = 5;
@Override
public void run() {
for(int j=0;j<500000;j++){
System.out.println("j="+j);
if(Thread.currentThread().interrupted()){
try {
throw new InterruptedException("thread is interrupted");
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
}
}
}
线程的阻塞
- public static void sleep(long millis) throws InterruptedException
- 阻塞当前线程,不释放锁,睡醒后进入就绪状态
- 捕获InterruptedException
- public static void yield()
- 当前线程进入就绪态,不抛出异常
- 把机会让给相同或者更高优先级的线程,重新争夺
- public void join()
- 在当前线程中调用另一个线程的join()方法,当前线程转入阻塞状态,直到另一个线程结束,当前线程再由阻塞转为就绪状态。
- public void wait()
- 属于Object类的方法,在同步方法或同步块中使用,释放锁
- 使当前拥有对象锁的线程等待,直到其他线程调用notify()
- synchronized
- 多线程访问同一份资源,保证线程安全,同步粒度太小易造成死锁
- 同步方法; 同步代码块 (引用类型,this,类.class)
线程的状态
![这里写图片描述](https://img-blog.csdn.net/20170926120230468?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvTWFnaWNfbWVsbG93/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
线程的信息
- public Thread(Runnable target, String name);
- public final void setName(String name);
- public final String getName();
- public static Thread currentThread()
- public final void setPriority(int newPriority);
- public final int getPriority();
- public final boolean isAlive ();
- public final boolean isDaemon(): //是否是守护线程
- public void setDaemon(boolean on) //在start()方法调用前设置
线程的同步
- synchronized
- 当一个线程访问object的一个synchronized时,另一个线程仍然可以访问该object中的非synchronized
- synchronized关键字不能继承
- 生产者消费者模式解决死锁:wait()/notify()
public class MyLearn {
public static void main(String[] args) throws Exception {
burgerStack bs=new burgerStack();
producer p=new producer(bs);
consumer c=new consumer(bs);
Thread tp=new Thread(p);
Thread tc=new Thread(c);
tp.start();
tc.start();
}
}
class producer implements Runnable {
burgerStack bs=null;
public producer(burgerStack bs) {
super();
this.bs = bs;
}
@Override
public void run() {
for(int i=0;i<20;i++){
burger b=new burger(i);
bs.push(b);
System.out.println("produce"+b.id);
}
}
}
class consumer implements Runnable{
burgerStack bs=null;
public consumer(burgerStack bs) {
super();
this.bs = bs;
}
@Override
public void run() {
for(int i=0;i<20;i++){
burger b=bs.pop();
System.out.println("consume"+b.id);
}
}
}
class burger {
int id;
public burger(int id) {
this.id = id;
}
}
class burgerStack {
burger[] burgerArr = new burger[6];
int index = 0;
public synchronized void push(burger in) {
while(index==burgerArr.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
burgerArr[index] = in;
index++;
}
public synchronized burger pop() {
while(index==0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
index--;
return burgerArr[index];
}
}