线程切换 java_Java线程切换执行

该博客展示了如何使用Java Swing创建GUI,并通过按钮控制两个线程的交替执行。线程一和线程二在特定状态(status变量)下执行,通过改变status值实现线程间的切换。用户可以通过点击按钮来激活相应的线程,实现线程执行的控制。
摘要由CSDN通过智能技术生成

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();

}

});

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值