线程
线程:一个进程当中不同的执行路径
像我们以前写的程序都是单线程的
线程的两种开启方法:
- 一种就是实现Runnable接口 implements Runnable
- 就是继承Thread类 extends Thread
两个例题
public class Test13 {
public static void main(String args[]) {
Thread t1 = new Thread(new T("t1"));
Thread t2 = new Thread(new T("t2"));
t1.start();
t2.start();
}
}
class T implements Runnable {
String no;
public T(String no){
this.no = no;
}
public void run() {
for(int i=0;i<100;i++){
//try{
//if(i%50==0){
//Thread.sleep(3999);
//}
//}catch(Exception e){
//}
if(i%10==0){
Thread.yield();
}
System.out.println(no+":"+i);
}
}
}
public class Test13a{
public static void main (String args[]){
T t1 = new T("t1");
T t2 = new T("t2");
t1.start();
t2.start();
}
}
class T extends Thread {
String no ;
public T(String no){
this.no = no;
}
public void run(){
for(int i=0;i<100;i++){
System.out.println(no+":"+i);
}
}
}
线程中要执行的类容必须写在线程体中
public void run(){}
只读锁解决线程同步的问题(火车票、银行取钱,哲学家吃饭)
synchronized 关键字
进程死锁例题
public class Test13b {
public static void main (String args[]){
T t2 = new T("t2",2);
Thread t1 = new Thread( );
Thread thread = new Thread(t2);
t1.start();
thread.start();
}
}
class T implements Runnable {
static Object o1 = new Object();
static Object o2 = new Object();
int flag;
String no ;
public T(String no,int flag){
this.no = no;
this.flag = flag;
}
public void run(){
if(flag==1){
synchronized(o1){
System.out.println(no+":o1");
synchronized(o2){
System.out.println(no+":o2");
}
}
}
else if(flag==2){
synchronized(o2){
System.out.println(no+":o2");
synchronized(o1){
System.out.println(no+":o1");
}
}
}
}
}