Java多執行緒
Thread類中的主要方法
- start():開啟執行緒
- run():繼承重寫run()
- currentThread():返回當前執行緒
- getName():返回執行緒名
- setName():設定執行緒名
- yield():釋放cpu執行權
- b.join():a執行緒阻塞並等待b執行緒執行完成
- stop():已過時,強制結束執行緒
- sleep():睡眠ms
- isAlive():是否存活
建立方式,jdk5.0前兩種,jdk5.0後兩種
- 繼承Thread類
- 實現Runnable介面
- 實現Callable介面
- 執行緒池
1.繼承Thread的方法
class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() +
":" + i);
}
}
}
}
public class MyThreadTest1 {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.setName("thread1");
t1.start();
}
}
2.實現Runnable介面的方法
class MyThread2 implements Runnable{
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() +
":" + i);
}
}
}
}
public class MyThreadTest2 {
public static void main(String[] args) {
MyThread2 m1 = new MyThread2();
Thread t1 = new Thread(m1);
t1.setName("thread1");
t1.start();
}
}
3.實現Callable介面的方法
class MyThread3 implements Callable {
@Override
public Object call() throws Exception {
int sum = 0;
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
sum += i;
System.out.println(Thread.currentThread().getName() +
":" + i);
}
}
return sum;
}
}
public class MyThreadTest3 {
public static void main(String[] args) {
FutureTask futureTask = new FutureTask(new MyThread3());
Thread t1 = new Thread(futureTask);
t1.setName("thread1");
t1.start();
try {
System.out.println(futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
4.使用執行緒池建立執行緒
class MyThread4 implements Runnable{
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
if (i % 2 != 0) {
System.out.println(Thread.currentThread().getName() +
":" + i);
}
}
}
}
class MyThread5 implements Callable{
@Override
public Object call() throws Exception {
int sum = 0;
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
sum += i;
System.out.println(Thread.currentThread().getName() +
":" + i);
}
}
return sum;
}
}
public class MyThreadTest4 {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(10);
service.execute(new MyThread4());
Future future = service.submit(new MyThread5());
try {
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
service.shutdown();
}
}
執行緒同步方法:
- Synchronized (同步程式碼塊,同步方法)同步監視器多個執行緒共用一個(共享資料時)
- Lock介面的實現類ReentrantLock物件的方法,lock.lock()、lock.unlock()
執行緒通訊方法:
- wait() 阻塞
- notify()/notifyAll() 喚醒