1.Runable與Thread#
Thread類是實(shí)現(xiàn)了Runable接口。
class TestRun implements Runnable {
private int i = 0;
@Override
public void run() {
while(i < 100) {
i ++;
System.out.println("run");
Thread.yield();
}
}
}
public class Client {
public static void main(String args[]) {
/*Context context = new Context();
context.setState(Context.concreteState1);
context.handler2();
context.handler1();*/
TestRun tr = new TestRun();
tr.run();
Thread t = new Thread(new TestRun());
//設(shè)置為后臺(tái)執(zhí)行
t.setDaemon(true);
//與主線程并發(fā)執(zhí)行
t.start();
System.out.println("main");
}
}
2.Executors#
class TestRun implements Runnable {
private int i = 0;
private int n = 0;
public TestRun(int n){
this.n = n;
}
@Override
public void run() {
while(i < 100) {
i ++;
System.out.println("run" + n);
Thread.yield();
}
}
}
public class Client {
public static void main(String args[]) {
//一個(gè)線程管理工具類
//ExecutorService ex = Executors.newCachedThreadPool();
//定義線程數(shù)量
ExecutorService ex = Executors.newFixedThreadPool(3);
for(int i = 0; i <= 5; i++) {
ex.execute(new TestRun(i));
}
ex.shutdown();
}
}
3.Callable#
Callable接口可以處理具有返回值的線程。只能通過ExecutorService.submit()函數(shù)啟動(dòng)
class TestCall implements Callable<String> {
private StringBuilder sb = new StringBuilder("Callable");
private int id;
public TestCall(int id) {
this.id = id;
}
@Override
public String call() throws Exception {
sb.append(id);
return sb.toString();
}
}
public class Client {
public static void main(String args[]) {
ExecutorService ex = Executors.newCachedThreadPool();
ArrayList<Future<String>> results = new ArrayList<Future<String>>();
for(int i = 0; i <= 1000; i++) {
results.add(ex.submit(new TestCall(i)));
}
for(Future<String> fs : results) {
try {
System.out.println(fs.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
ex.shutdown();
}
}
}
}
4.共享資源#
//一個(gè)加鎖對(duì)象中某個(gè)加鎖方法被訪問,則整個(gè)對(duì)象被加鎖
synchronized void f() {}
synchronized void g() {}
//整個(gè)類被加鎖
synchronized static void t() {}
//顯示加鎖
lock.lock()
lock.unlock()
``