package com.what21.thread11;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public final class ThreadSwitchTest01 {
private static int status = 0;
/**
*
*/
public static void launchGUI(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Java线程切换");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
// 线程
Thread thread1 = new Thread1("线程一");
thread1.start();
Thread thread2 = new Thread2("线程二");
thread2.start();
//
JButton bnt1 = new JButton("执行线程一");
bnt1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
status=1;
}
});
panel.add(bnt1);
//
JButton bnt2 = new JButton("执行线程二");
bnt2.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
status=2;
}
});
panel.add(bnt2);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
private static class Thread1 extends Thread{
private String name;
private Thread1(String name){
this.name =name;
}
public void run() {
while(true){
while(status!=1){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 执行内容
System.out.println(this.name + ",执行中......");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private static class Thread2 extends Thread{
private String name;
private Thread2(String name){
this.name =name;
}
public void run() {
while(true){
while(status!=2){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 执行内容
System.out.println(this.name + ",执行中......");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
launchGUI();
}
});
}
}