public class Test{
public static void main(String[] args) throws Exception{
TestThread testThread = new TestThread();
testThread.run();
}
}
運作結果:
Java線程篇
2.實作Runnable接口
經典的生産者和消費者
class Product implements Runnable{//生産者
private Message message;
Product(Message message) {
this.message = message;
}
public void run() {
for (int x = 0 ; x < 100 ; x++){
if (x % 2 == 0){
this.message.set("生産者","生産");
}else {
this.message.set("消費者","消費");
}
}
}
}
----
class Consumer implements Runnable{//消費者
private Message message;
public Consumer(Message message) {
this.message = message;
}
public void run() {
for (int x = 0 ; x < 100 ; x++){
System.out.println(this.message.get());
}
}
}
----
class Message{ //消息中心
private String title;
private String content;
private boolean flag = true;//表示生産或者消費的形式
// flag = true 允許生産,不允許消費 flag= false 允許消費,不允許生産
synchronized void set(String title, String content){
if (!flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.title = title;
this.content = content;
this.flag = false; //生産完成
notify();//喚醒等待的線程
}
synchronized String get(){
if (flag == true){
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
return this.title + " ------------ "+this.content;
}finally {
this.flag = true; // 可繼續生産
notify();//喚醒等待線程
}
}
}
----
public class Producer {
public static void main(String[] args) throws Exception{
Message message = new Message();
new Thread(new Product(message),"生産者").start();//啟動生産者線程
new Thread(new Consumer(message),"消費者").start();//啟動消費者線程
}
}
運作結果
Java線程篇
3.實作Callable接口
class TheThread implements Callable<String>{
private boolean flag = false;
@Override
public String call() throws Exception {
synchronized (this){
if (this.flag==false){
this.flag = true;
return Thread.currentThread().getName()+"搶答成功";
}else {
return Thread.currentThread().getName()+"搶答失敗";
}
}
}
}
public class Competition {
public static void main(String[] args) throws ExecutionException, InterruptedException {
TheThread theThread = new TheThread();
FutureTask<String> futureTaskA = new FutureTask<>(theThread);
FutureTask<String> futureTaskB = new FutureTask<>(theThread);
FutureTask<String> futureTaskC = new FutureTask<>(theThread);
new Thread(futureTaskA,"競賽者A").start();
new Thread(futureTaskB,"競賽者B").start();
new Thread(futureTaskC,"競賽者C").start();
System.out.println(futureTaskA.get());
System.out.println(futureTaskB.get());
System.out.println(futureTaskC.get());
}
}
Java線程篇
4.使用線程池
class ExecutorTest{
public static void main(String[] args) {
// 建立線程池
ThreadPoolExecutor service = new ThreadPoolExecutor(5, 200,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(1024),
new ThreadFactoryBuilder().setNameFormat("test-thread-pool-%d").build(),
new ThreadPoolExecutor.AbortPolicy());
Runnable runnable = () -> {
try {
TimeUnit.SECONDS.sleep(1);
System.out.println("線程1執行");
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Runnable runnable1 = () -> {
try {
TimeUnit.SECONDS.sleep(2);
System.out.println("線程2執行");
} catch (InterruptedException e) {
e.printStackTrace();
}
};
int num = 10;
for (int i = 0; i < num; i++) {
service.execute(runnable);
service.execute(runnable1);
}
}
}
public class Volatile{
public static void main(String[] args) throws Exception{
MyThread myThread = new MyThread();
new Thread(myThread,"票販子A").start();
new Thread(myThread,"票販子B").start();
new Thread(myThread,"票販子C").start();
}
}
public class Daemon {
public static void main(String[] args) throws Exception{
Thread userThread = new Thread(() -> {
for (int x = 0 ; x < 10 ; x++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在執行 x = " + x);
}
},"執行線程");
Thread daemonThread = new Thread(() -> {
for (int x = 0 ; x < Integer.MAX_VALUE ; x++){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在執行 x = " + x);
}
},"守護線程");
daemonThread.setDaemon(true);//将daemonThread設為守護線程
userThread.start();
daemonThread.start();
}
}
Java線程篇
在Thread類提供了以下的守護線程的操作方法,可自行檢視源碼
設定為守護線程:
public final void setDaemon(boolean on) {
checkAccess();
if (isAlive()) {
throw new IllegalThreadStateException();
}
daemon = on;
}
判斷是否為守護線程
public final boolean isDaemon() {
return daemon;
}
停止線程
public class StopThread {
public static boolean flag = true;
public static void main(String[] args) throws Exception{
new Thread(() -> {
long num = 0;
while (flag){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在執行 num = " + num++);
}
},"執行線程").start();
Thread.sleep(200);//線程運作200毫秒
flag = false;//停止線程
}
}