一 实现线程两种方式
1.定义Thread类的子类,并重写该类的run方法,该run方法的方法体就代表了线程要完成的任务。因此把run()方法称为执行体。
Thread thread = new Thread() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1:"+Thread.currentThread().getName());
}
}
};
thread.start();
2.定义runnable接口的实现类,并重写该接口的run()方法,该run()方法的方法体同样是该线程的线程执行体。
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("2:"+Thread.currentThread().getName());
}
}
});
thread2.start();
}
二 线程互斥,保证同一个线程执行完
案例:打印两个人的名字拼音,保证同一个人打印完,不受另一个的影响
public class TraditionalThreadSynchronnized {
public static void main(String[] args) {
new TraditionalThreadSynchronnized().init();
}
private void init() {
final OutPuter outputer = new OutPuter();
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("pengyunle");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output("lichengli");
}
}
}).start();
}
class OutPuter{
public synchronized void output(String name) {
int len = name.length();
for(int i= 0;i<len;i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
三 timer计数器
四 子线程循环10次,主线程循环100次,接着又回到子线程循环10次,接着再回到主线程循环100次,如此循环50次
//子线程循环10次,主线程循环100次,接着又回到子线程循环10次,接着再回到主线程循环100次,如此循环50次
public static void main(String[] args) {
final Business business =new Business();
new Thread(new Runnable() {
@Override
public void run() {
for(int j = 1; j <=50 ;j++) {
business.sub(j);
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int j = 1; j <=50 ;j++) {
business.main(j);
}
}
}).start();
}
}
class Business{
private boolean shelud = true;
public synchronized void sub(int j) {
while(!shelud) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int i=1;i<=10;i++) {
System.out.println("sub thread sequnce of "+i+","+"loop of "+j);
}
shelud = false;
this.notify();
}
public synchronized void main(int j) {
while(shelud) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int i=1;i<=100;i++) {
System.out.println("main thread sequnce of "+i+","+"loop of "+j);
}
shelud = true;
this.notify();
}
}