synchronized : 同步锁
线程启动:start()
线程休眠:sleep(1000) 1s
线程等待:wait() 需要在同步内,否则报异常
线程唤醒:notify()需要在同步内,否则报异常
线程中断退出:stop();Thread.interrupt()
线程加入:thread.Join把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。
t.join(); //使调用线程 t 在此之前执行完毕。
t.join(1000); //等待 t 线程,等待时间是1000毫秒
总结1:线程的创建
public class ThreadMain {
public static void main(String[] args) {
// TODO 创建线程的几种方法
// 一:
// 1.通过创建继承thread的类ThreadCreate
ThreadCreate thread = new ThreadCreate();
thread.start();
// 2.创建一个Thread的匿名子类
Thread thread2 = new Thread(){
public void run() {
System.out.println("thread2 Running");
}
};
thread2.start();
// 二:
// 1.通过创建实现runable的类ThreadCreate
// 2.实现实现了Runnable接口的匿名类
Runnable myRunnable = new Runnable(){
public void run(){
System.out.println("thread3 running");
}
};
Thread thread3 = new Thread(myRunnable);
thread3.start();
}
}
//ThreadCreate类: public class ThreadCreate extends Thread {
public void run() {
System.out.println("ThreadCreate running");
}
总结2:线程锁,线程sleep以及wait和notify的运用
public class ThreadWaitNotify {
/**
* 线程锁
*/
private static Object object = new Object();
public static void main(String[] args) {
Runnable runnable1 = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (object) {
System.out.println("进入线程");
System.out.println("线程睡眠1s");
try {
Thread.sleep(1000);
System.out.println("线程退出睡眠");
System.out.println("线程进入等待");
object.wait();
System.out.println("线程进入等待test");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Runnable runnable2 = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (object) {
System.out.println("进入线程2");
try {
System.out.println("线程取消等待");
object.notify();
System.out.println("线程取消等待ok");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable2);
thread1.start();
thread2.start();
}
}
总结3:多线程购票的例子:
public class buyTicket implements Runnable{
private int ticket = 100; //5张票
@Override
public void run() {
while(true){
synchronized(this){
if(ticket>0){
System.out.println(Thread.currentThread().getName()+"正在售卖第"+ticket+"张票");
ticket--;
}else{
System.out.println(Thread.currentThread().getName()+"退出售票");
break;
}
}
}
}
public static void main(String [] args) {
buyTicket my = new buyTicket();
new Thread(my, "1号窗口").start();
new Thread(my, "2号窗口").start();
new Thread(my, "3号窗口").start();
new Thread(my, "4号窗口").start();
}
}
其他参考资料:https://zhuanlan.zhihu.com/p/27836782