public class Main {
public static void main(String[] args) throws InterruptedException {
Thread myTread=new Thread(){
public void run(){
System.out.println("hello new thread");
}
};
myTread.start();
Thread.yield(); // 通知调度器,当前线程想要让出对处理器的占用
System.out.println("hello main thread");
myTread.join();
}
}
没有锁,线程不安全
import java.util.TreeMap;
public class Main {
public static void main(String[] args) throws InterruptedException {
class Counter{
private int count=0;
public void increment(){++count;}
public int getCount(){return count;}
}
final Counter counter = new Counter();
class CountingThread extends Thread{
public void run(){
for (int i = 0; i < 10000; i++) {
counter.increment();
}
}
}
CountingThread t1 = new CountingThread();
CountingThread t2 = new CountingThread();
t1.start();t2.start();
t1.join();t2.join();
System.out.println(counter.getCount());
}
}
加上同步瞬间好了
public synchronized void increment(){++count;}
死锁,不能中断
public class Uninteruptible {
public static void main(String[] args) throws InterruptedException {
final Object o1 = new Object();
final Object o2 = new Object();
Thread t1=new Thread(){
public void run(){
try {
synchronized (o1){
Thread.sleep(1000);
synchronized (o2){}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread t2=new Thread(){
public void run(){
try {
synchronized (o2){
Thread.sleep(1000);
synchronized (o1){}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t1.start();
t2.start();
Thread.sleep(2000);
t1.interrupt();
t2.interrupt();
t1.join();
t2.join();
}
}
死锁,可以中断
import java.util.concurrent.locks.ReentrantLock;
public class Uninteruptible {
public static void main(String[] args) throws InterruptedException {
final ReentrantLock l1=new ReentrantLock();
final ReentrantLock l2=new ReentrantLock();
Thread t1=new Thread(){
public void run(){
try {
l1.lockInterruptibly();
Thread.sleep(1000);
l2.lockInterruptibly();
l2.unlock();
l1.unlock();
} catch (InterruptedException e) {
System.out.println("t1 interrupted");
e.printStackTrace();
}
}
};
Thread t2=new Thread(){
public void run(){
try {
l2.lockInterruptibly();
Thread.sleep(1000);
l1.lockInterruptibly();
l1.unlock();
l2.unlock();
} catch (InterruptedException e) {
System.out.println("t2 interrupted");
e.printStackTrace();
}
}
};
t1.start();
t2.start();
Thread.sleep(2000);
t1.interrupt();
t2.interrupt();
t1.join();
t2.join();
}
}