Java实现多线程方式有以下两种:
public class HelloWordThread implements Runnable{
public void run(){
System.out.println("HelloWordThread.run()");
System.out.println("threadName:"+Thread.currentThread().getName());
System.out.println("threadState:"+Thread.currentThread().getState());
}
}
public class CounterThread extends Thread {
@Override
public void run(){
System.out.println("threadName:"+Thread.currentThread().getName());
System.out.println("threadState:"+Thread.currentThread().getState());
}
}
线程并发保证数据一致性的关键字:synchronized
可以加在对象的方法上:
public class Counter {
private int counter=0;
public synchronized void incr() {
this.counter++;
}
public synchronized int get() {
return this.counter;
}
}
或者
public class Counter {
private int counter=0;
public void incr() {
synchronized(this){
this.counter++;
}
}
public int get() {
synchronized(this){
return this.counter;
}
}
}
切记 synchronized同步的对象是当前对象。
保证同步的同时,就会有资源消耗,java提供了一个轻量级的关键字:volatile
PS:其他对线程对象的实现方法:start、sleep、join等与C#基本一致。
关于interrupt方法:
1、此方法不会中断线程,只是一个协调机制。设置一个线程中断标志位。具体什么时候中断,线程会参考这个标志位。
所以当不知道线程在做什么事时,不能贸然调用此方法。